新秀需要一些帮助。有人可以提供一个查询来轻松计算,然后按月匹配两个条件的记录制表,以避免使用像这样笨拙的重复代码......
SELECT
SUM( CASE
WHEN extract( YEAR FROM `date` ) = "2017"
AND extract( MONTH FROM `date` ) = "07"
AND `conditionA` = "A"
AND `conditionB` = "B"
THEN 1 else 0 END )
AS 2017_07
SUM( CASE
WHEN extract( YEAR FROM `date` ) = "2017"
AND extract( MONTH FROM `date` ) = "08"
AND `conditionA` = "A"
AND `conditionB` = "B"
THEN 1 else 0 END )
AS 2017_08
SUM( CASE
WHEN extract( YEAR FROM `date` ) = "2017"
AND extract( MONTH FROM `date` ) = "09"
AND `conditionA` = "A"
AND `conditionB` = "B"
THEN 1 else 0 END )
AS 2017_09
FROM `datatable`
答案 0 :(得分:2)
将数据放入行而不是列:
SELECT extract( YEAR FROM `date` ) as yyyy, extract( MONTH FROM `date` ) as mm,
COUNT(*)
FROM datatable
WHERE `conditionA` = 'A' AND `conditionB` = 'B'
GROUP BY extract( YEAR FROM `date` ), extract( MONTH FROM `date` )
ORDER BY yyyy, mm ;