将2年的数据收集到一个结果行中

时间:2018-07-06 13:21:20

标签: mysql sql

我有这个查询:

SELECT BC_PID, Year, Period, 
CASE WHEN Year = 2017 THEN SUM(Allin+Basis+Entry+IFNULL(3CXUsers, 0)) END as '2017', 
CASE WHEN Year = 2018 THEN SUM(Allin+Basis+Entry+IFNULL(3CXUsers, 0)) END as '2018'  
FROM ext_partnertotals WHERE
(Year = '2018' OR Year = '2017') AND Period = 6
GROUP BY BC_PID, Year

结果是这样的:
enter image description here

现在,我想将BC_PID的2行变成一行。
这样一来,每行BC_PID的数字都将分别为2017和2018。
我目前总共有2行。

它应该给出:

  BC_PID |Period|2017 |2018
   2.001 |6     |1.744|2.444
 100.003 |6     |0    |0

检查此SQLfiddle: http://sqlfiddle.com/#!9/4c9b5/1

2 个答案:

答案 0 :(得分:1)

微调小提琴:

SELECT BC_PID, Period,
SUM(CASE WHEN Year = 2017 THEN Allin+Basis+Entry+IFNULL(3CXUsers, 0) ELSE 0 END) as '2017',
SUM(CASE WHEN Year = 2018 THEN Allin+Basis+Entry+IFNULL(3CXUsers, 0) ELSE 0 END) as '2018'
FROM ext_partnertotals
WHERE (Year = '2018' OR Year = '2017') AND Period = 6
GROUP BY BC_PID, Period

答案 1 :(得分:0)

SELECT BC_PID, Year, Period, 
CASE WHEN Year IN (2017,2018) 
   THEN SUM(Allin+Basis+Entry+IFNULL(3CXUsers, 0)) END as '2017_8'
FROM ext_partnertotals 
WHERE (Year = '2018' OR Year = '2017') 
AND Period = 6 
GROUP BY BC_PID, Year