此问题已在此处有答案:
How can I return pivot table output in MySQL?(10个答案)
14天前关闭
Expected使用group by和case,我能够获得一个时间间隔内每个产品的统计结果。但是我希望每个间隔的结果是水平的(上图),注意使用下面的查询我们可以垂直地得到结果:
SELECT
p.category,
(CASE
WHEN TIMESTAMPDIFF(YEAR, p.dt, CURDATE()) BETWEEN 1 AND 5 THEN '1-5'
WHEN TIMESTAMPDIFF(YEAR, p.dt, CURDATE()) BETWEEN 6 AND 9 THEN '6-9'
WHEN TIMESTAMPDIFF(YEAR, p.dt, CURDATE()) BETWEEN 10 AND 15 THEN '10-15'
ELSE '16-20'
END) as Interval,
COUNT(*) AS totalNbr
FROM product p
GROUP BY p.category, Interval
我试过使用联盟,但它还没有工作。
1条答案
按热度按时间2ekbmq321#
使用条件聚合。在MySQL中: