如何在不同的列中组合具有不同值的2行

时间:2017-05-28 03:47:52

标签: mysql sql

我希望将2行组合在一起,但在不同的列中具有不同的值。像这样:

tgl         qty_NEW MIO M3 125 CW-OTR  qty_NEW-SOUL-GT-125-OTR  
----------  -------------------------  -------------------------
2016-05-01  0                          0                        
2016-05-02  0                          0                        
2016-05-05  0                          0                        
2016-05-09  0                          0                        
2016-05-10  2                          0                        
2016-05-10  0                          1                

2016-05-10也是如此,其值为2 - 0和0 - 1。

我想要的是这样的:

tgl         qty_NEW MIO M3 125 CW-OTR  qty_NEW-SOUL-GT-125-OTR  
----------  -------------------------  -------------------------
2016-05-01  0                          0                        
2016-05-02  0                          0                        
2016-05-05  0                          0                        
2016-05-09  0                          0                        
2016-05-10  2                          1                        

我使用的查询是这样的:

SELECT DISTINCT DATE(m.tgl_fj) AS tgl , 
CASE brg.nama_brg WHEN 'NEW MIO M3 125 CW-OTR' THEN SUM(d.qty) ELSE '0' END AS 'qty_NEW MIO M3 125 CW-OTR' , 
CASE brg.nama_brg WHEN 'NEW-SOUL-GT-125-OTR' THEN SUM(d.qty) ELSE '0' END AS 'qty_NEW-SOUL-GT-125-OTR' 
FROM tb_mt_fj m
LEFT OUTER JOIN tb_dt_fj_brg d
ON m.ucode_fj=d.ucode_fj
LEFT OUTER JOIN tb_m_brg brg
ON d.ucode_brg=brg.ucode_brg
LEFT OUTER JOIN tb_m_grp_brg grp
ON brg.ucode_grp_brg=grp.ucode_grp_brg
WHERE brg.ucode_grp_brg='11040000000089' AND MONTH(m.tgl_fj)=MONTH(NOW())
GROUP BY DATE(m.tgl_fj), brg.nama_brg
ORDER BY DATE(m.tgl_fj)

那么,如何使查询结果与我想要的相同?

1 个答案:

答案 0 :(得分:0)

此查询应该这样做

select tgl, sum(qty_NEW MIO M3 125 CW-OTR) as `left`, sum(qty_NEW-SOUL-GT-125-OTR) as `right` from `table` group by tgl