sql中的垂直和水平组

时间:2014-11-01 05:04:04

标签: sql

请考虑下表(表名:销售)

ID     Customer     Year     Amount
1         A         2012      1000
2         B         2012      2000
3         A         2012      1500
4         C         2013      1000
5         B         2013      2000

我正在寻找返回以下结果的查询:

Customer       Year2012      Year2013
A                2500           0
B                2000         2000
C                0            1000

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT Customer,ISNULL([2012],0)as [2012],ISNULL([2013],0)as [2013]
FROM (
    SELECT 
       Customer,[Year] as [year], Amount
    FROM Mytest
) as s
PIVOT(SUM(AMOUNT)
      FOR Year IN ([2012], [2013])) AS PVTTable

输出:

Customer    2012    2013
A          2500      0
B          2000     2000
C           0       1000

答案 1 :(得分:0)

select  Customer,
    SUM(case when Year = '2012' then Amount else 0 end) as 'Year2012',
    SUM(case when Year = '2013' then Amount else 0 end) as 'Year2013'
from Sale
group by Customer;

SQL小提琴 - http://sqlfiddle.com/#!2/f560b/4

答案 2 :(得分:-1)

执行以下代码:

SELECT * FROM customer 
PIVOT(SUM(Amount) FOR Year IN ([2012],[2013]))
AS PVTTable