我在SALES表中有以下数据:
Customer Year Amount'
1 2011 1500
1 2012 2000
1 2013 1900
2 2011 4500
2 2012 5000
2 2013 6000
使用以下查询:
SELECT * FROM SALES WHERE Year=2012
UNION
SELECT * FROM SALES WHERE Year=2013
我得到了这个结果:
Customer Year Amount
1 2012 2000
1 2013 1900
2 2012 5000
2 2013 6000
但是,现在我的问题是:我应该如何编写查询以获得如下结果?
Customer Amount2012 Amount2013
1 2000 1900
2 5000 6000
答案 0 :(得分:4)
您不需要使用UNION
来编写两个条件,您可以使用IN
谓词或WHERE Year = 2012 OR Year = 2013
执行此操作,然后使用CASE
表达式将每年的金额放在一个单独的栏目中:
SELECT
Customer,
MAX(CASE WHEN Year = 2012 THEN Amount ELSE 0 END) AS Amount2012,
MAX(CASE WHEN Year = 2013 THEN Amount ELSE 0 END) AS Amount2013
FROM SALES
WHERE Year IN(2012, 2013)
GROUP BY Customer;
或者,您可以使用PIVOT
表运算符将金额的行数转换为列,如下所示:
SELECT
Customer,
[2012] AS Amount2012,
[2013] AS Amount2013
FROM
(
SELECT *
FROM Sales
WHERE Year IN(2012, 2013)
) AS t
PIVOT
(
MAX(Amount)
FOR Year IN([2012], [2013])
) AS p;
这会给你:
╔═══════════╦═════════════╦════════════╗
║ CUSTOMER ║ AMOUNT2012 ║ AMOUNT2013 ║
╠═══════════╬═════════════╬════════════╣
║ 1 ║ 2000 ║ 1900 ║
║ 2 ║ 5000 ║ 6000 ║
╚═══════════╩═════════════╩════════════╝
答案 1 :(得分:1)
试试这个
SELECT Customer,
SUM(CASE WHEN Year=2012 then Amount else 0 END) Amoumt2012,
SUM(CASE WHEN Year=2013 then Amount else 0 END) Amoumt2013
FROM SALES WHERE Year in (2012 ,2013)
GROUP BY Customer