1

我已经建立了这个查询:

SELECT *
FROM 
(
   SELECT [VendorCode], [VendorName], 
      year(CheckDate) as 'year',
      left(datename(month,CheckDate),3) as [month], 
      [CheckSum] as 'Amount'
   FROM ocho 
   WHERE [Canceled] ='N'
) as abc
PIVOT
(
  SUM(Amount)
  FOR [month] IN (jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec)
) AS sumpivot

我得到一张表格,每个供应商都没有汇总到一行,每个供应商都在 12 个月或更短的时间内,这取决于我们用支票支付了他们多少个月。我试图通过 vendorcodeand进行分组,但name我失败了。

4

1 回答 1

0

我认为一切正常 -

询问:

DECLARE @temp TABLE
(
      VendorCode INT
    , VendorName NVARCHAR(50)
    , CheckDate DATETIME
    , Canceled CHAR(1)
    , [CheckSum] DECIMAL(10,2)
)

INSERT INTO @temp (VendorCode, VendorName, CheckDate, Canceled, [CheckSum])
VALUES 
    (1, '1', '20100101', 'N', 4),
    (2, '2', '20100303', 'N', 2),
    (2, '2', '20100601', 'N', 1),
    (2, '2', '20100604', 'N', 99)

SELECT *
FROM 
(
    SELECT 
          [VendorCode]
        , [VendorName]
        , [year] = YEAR(CheckDate)
        , [month] = LEFT(DATENAME(MONTH, CheckDate), 3) 
        , Amount = [CheckSum] 
    FROM @temp 
    WHERE Canceled = 'N'
) abc
PIVOT
(
    SUM(Amount)
    FOR [month] IN (
                jan, feb, mar, 
                apr, may, jun, 
                jul, aug, sep, 
                oct, nov, [dec])
) sumpivot

输出:

VendorCode  VendorName year   jan    feb   mar   apr   may   jun     jul   aug   sep   oct    nov    dec
----------- ---------- ------ ------ ----- ----- ----- ----- ------- ----- ----- ----- ------ ------ ------
1           1          2010   4.00   NULL  NULL  NULL  NULL  NULL    NULL  NULL  NULL  NULL   NULL   NULL
2           2          2010   NULL   NULL  2.00  NULL  NULL  100.00  NULL  NULL  NULL  NULL   NULL   NULL
于 2013-08-06T12:12:49.910 回答