我无法从下面列出的输入数据到输出数据中找出SQL的枢纽。
这是我的输入数据。
State MONTH YEAR CNT
---------------------------
NY MAR 2019 1
CA MAR 2018 3
CA JAN 2019 7
VA APR 2018 1
VA APR 2019 2
AZ APR 2019 4
AZ MAY 2019 5
输出数据:
2018 2019
state MAR APR JAN MAR APR MAY
AZ 4 5
CA 3 7
NY 1
VA 1 2
答案 0 :(得分:0)
对于SQL SERVER-您可以尝试执行此操作,尽管它将在不同的行中返回YEARS。
SELECT State,YEAR,
ISNULL(JAN,0) JAN,
ISNULL(FEB,0) FEB,
ISNULL(MAR,0) MAR,
ISNULL(APR,0) APR,
ISNULL(MAY,0) MAY
FROM
(
SELECT
State,
YEAR,
MONTH,
CNT
FROM your_table
) as s
PIVOT
(
SUM(CNT)
FOR MONTH IN ([MAR],[FEB],[JAN],[APR],[MAY])
) PVT
ORDER BY 2,1
答案 1 :(得分:-1)
您可以使用条件聚合:
select state,
sum(case when month = 'MAR' and year = 2018 then cnt end) as 2018_MAR,
sum(case when month = 'APR' and year = 2018 then cnt end) as 2018_APR,
sum(case when month = 'JAN' and year = 2019 then cnt end) as 2019_JAN,
sum(case when month = 'MAR' and year = 2019 then cnt end) as 2019_MAR,
sum(case when month = 'APR' and year = 2019 then cnt end) as 2019_APR,
sum(case when month = 'MAY' and year = 2019 then cnt end) as 2019_MAY
from t
group by state;