MySQL pivot:在同一行显示值

时间:2018-02-20 20:25:24

标签: mysql pivot

使用下表:

CREATE TABLE `STOCK_LEVEL`(
  `ID` int(11),
  `Date` date,
  `ProductCode` varchar(50),
  `Quantity` int(10)
)

INSERT INTO `STOCK_LEVEL` (`ID`, `Date`, `ProductCode`, `Quantity`) VALUES
(1, '2018-02-10', 'PROD01', 15),
(2, '2018-02-10', 'PROD02', 90),
(3, '2018-02-14', 'PROD03', 5),
(4, '2018-02-14', 'PROD01', 11);

我希望在给定的一天看到给定产品的库存水平,因此我按产品创建了一个查询:

SELECT 
    Date,
    (Case when ProductCode = 'PROD01' then Quantity else 0 end) As 'AlphaProduct', 
    (Case when ProductCode = 'PROD02' then Quantity else 0 end) As 'BetaProduct', 
    (Case when ProductCode = 'PROD03' then Quantity else 0 end) As 'GammaProduct'

FROM STOCK_LEVEL

WHERE Date IN( '2018-02-10', '2018-02-14')

这将给我一个这样的结果:

+------------+--------------+-------------+--------------+
| Date       | AlphaProduct | BetaProduct | GammaProduct |
+------------+--------------+-------------+--------------+
| 2018-02-10 | 15           | 0           | 0            |
+------------+--------------+-------------+--------------+
| 2018-02-10 | 0            | 90          | 0            |
+------------+--------------+-------------+--------------+
| 2018-02-14 | 0            | 0           | 5            |
+------------+--------------+-------------+--------------+
| 2018-02-14 | 11           | 0           | 0            |
+------------+--------------+-------------+--------------+

我可能遗漏了一些基本的东西,但有没有办法让这个按日期分组如下:(我不能GROUP BY,因为没有聚合?)

+------------+--------------+-------------+--------------+
| Date       | AlphaProduct | BetaProduct | GammaProduct |
+------------+--------------+-------------+--------------+
| 2018-02-10 | 15           | 90          | 0            |
+------------+--------------+-------------+--------------+
| 2018-02-14 | 11           | 0           | 5            |
+------------+--------------+-------------+--------------+

1 个答案:

答案 0 :(得分:3)

使用a(假)聚合函数和分组

SELECT 
Date,
max(Case when ProductCode = 'PROD01' then Quantity else 0 end) As 'AlphaProduct', 
max(Case when ProductCode = 'PROD02' then Quantity else 0 end) As 'BetaProduct', 
max(Case when ProductCode = 'PROD03' then Quantity else 0 end) As 'GammaProduct'

FROM STOCK_LEVEL

WHERE Date IN( '2018-02-10', '2018-02-14')
group by Date