gpt4 book ai didi

mysql - 使用SELECT结果做表

转载 作者:行者123 更新时间:2023-11-28 23:25:00 24 4
gpt4 key购买 nike

我有一个这样的表:

enter image description here

我想执行以下 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|...

最佳答案

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')

如果 AE 列中的唯一值是 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')

关于mysql - 使用SELECT结果做表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39742330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com