试图在MYSQL中获得转置表

时间:2017-05-23 09:20:09

标签: mysql

以下是用于获取表格转置的查询。

SELECT  month,
        CASE WHEN year = '2016-17' THEN sum(Amt) end,
        CASE WHEN year = '2017-18' THEN sum(Amt) end
FROM   
(   select year, month, type, sum(item_amt) as Amt 
    from `dummy` 
    where type = 'XYZ' AND party_code != 'Interunit' AND (item_acc_code='301010100001' OR item_acc_code='301010100002') AND (YEAR(inv_date)=YEAR(CURDATE()) OR YEAR(inv_date)=YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))) 
    group by month,year
) T
group by month,year

当前输出

month || CASE WHEN year='2016-17' || CASE WHEN year='2017-18'
Apr   || 1487                     || NULL 
Apr   || NULL                     || 1847
May   || 1591                     || NULL
May   || NULL                     || 1234

期望输出

month || 2016-17 || 2017-18
Apr   || 1487    || 1847 
May   || 1591    || 1234

我们面临两个问题: - a)不能为输出列指定别名b)通过不考虑NULL值,逐个月的值应显示在一行中。

2 个答案:

答案 0 :(得分:1)

当您在案例陈述中选择适当的年份时,您应该从外部分组中删除年份。至于别名 - 在case语句

周围使用括号
SELECT  month,
        (CASE WHEN year = '2016-17' THEN sum(Amt) end) as year1617,
        (CASE WHEN year = '2017-18' THEN sum(Amt) end) as year1718
FROM   
(   select year, month, type, sum(item_amt) as Amt 
    from `dummy` 
    where type = 'XYZ' AND party_code != 'Interunit' AND (item_acc_code='301010100001' OR item_acc_code='301010100002') AND (YEAR(inv_date)=YEAR(CURDATE()) OR YEAR(inv_date)=YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))) 
    group by month,year
) T
group by month

答案 1 :(得分:1)

尝试以下查询。我认为您不需要使用子查询

SELECT
    MONTH,
    SUM(CASE WHEN YEAR = '2016-17' THEN item_amt ELSE 0 END) '2016-17', 
    SUM(CASE WHEN YEAR = '2017-18' THEN item_amt ELSE 0 END) '2017-18'
FROM dummy
WHERE TYPE = 'XYZ' AND
      party_code != 'Interunit' AND
      (item_acc_code='301010100001' OR item_acc_code='301010100002') AND
      (YEAR(inv_date)=YEAR(CURDATE()) OR YEAR(inv_date)=YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))) 
GROUP BY MONTH