显示结果

时间:2014-12-26 10:54:18

标签: sql-server tsql

我的表是这样的:

Sitecode    Month  Amount
--------    -----  ------
XX          Jan     1000
XX          Jan     3000
XX          Apr     3000
XX          Apr     1000

我想要的是,显示如下结果:

Sitecode    MonthJAN   MonthAPR
--------    --------   --------
XX          1000       3000
XX          3000       1000

2 个答案:

答案 0 :(得分:0)

您可以使用PIVOT条款:

Pivot tables in SQL Server. A simple sample.

答案 1 :(得分:0)

您可以使用PIVOT.

实现此目的

Fiddler Demo

CREATE TABLE Sample
(
    SiteCode VARCHAR(100),  
    Month VARCHAR(100),    
    Amount INT
)

INSERT INTO Sample VALUES('XX', 'Jan', 1000)
INSERT INTO Sample VALUES('XX', 'Jan', 3000)  
INSERT INTO Sample VALUES('XX', 'Apr', 3000)
INSERT INTO Sample VALUES('XX', 'Apr', 1000)

SELECT P.SiteCode, P.Jan AS MonthJan, P.Apr AS MonthApr FROM 
(
    SELECT *, 
     ROW_NUMBER() OVER (PARTITION BY [Month] ORDER BY [Month]) AS Num 
    FROM Sample
) AS A
PIVOT (MAX(A.Amount) FOR A.Month IN ([Jan], [Apr])) AS P