我有一张这样的表:
我想执行以下SELECT语句:
SELECT count(*) from table WHERE A=1 and date between 2013-02 and 2013-03
SELECT count(*) from table WHERE A=1 and date between 2013-03 and 2013-04
SELECT count(*) from table WHERE A=1 and date between 2013-04 and 2013-05
....
SELECT count(*) from table WHERE B=1 and date between 2013-02 and 2013-03
SELECT count(*) from table WHERE B=1 and date between 2013-03 and 2013-04
SELECT count(*) from table WHERE B=1 and date between 2013-04 and 2013-05
...etc
什么是最快的查询,我可以将结果安排在如下表格中:
date |A=1 |B=1 |C=1 |...
2013-Feb|count|count|count|
2013-Mar|count|...
答案 0 :(得分:1)
SELECT DATE_FORMAT(date, '%Y-%m'),
SUM(CASE WHEN A=1 THEN 1 END) AS Acount,
SUM(CASE WHEN B=1 THEN 1 END) AS Bcount,
SUM(CASE WHEN C=1 THEN 1 END) AS Ccount,
SUM(CASE WHEN D=1 THEN 1 END) AS Dcount,
SUM(CASE WHEN E=1 THEN 1 END) AS Ecount
FROM table
GROUP BY DATE_FORMAT(date, '%Y-%m')
如果A
到E
列中的唯一值为0或1(或可能是NULL
),那么我们可以简化为:
SELECT DATE_FORMAT(date, '%Y-%m'),
SUM(A) AS Acount,
SUM(B) AS Bcount,
SUM(C) AS Ccount,
SUM(D) AS Dcount,
SUM(E) AS Ecount
FROM table
GROUP BY DATE_FORMAT(date, '%Y-%m')
答案 1 :(得分:0)
嗨,您可以拥有 GROUP BY 功能
SELECT
to_char(date,'YYYY-MM') as date,
CASE WHEN A=1 THEN COUNT(A) END as A ,
CASE WHEN B=1 THEN COUNT(B) END as B ,
CASE WHEN C=1 THEN COUNT(C) END as C ,
CASE WHEN D=1 THEN COUNT(D) END as D ,
CASE WHEN E=1 THEN COUNT(E) END as E
from table_name group by date order by date
此查询根据年份和月份对列进行分组,并为您提供结果