我有一张这样的桌子
ID,date,state
1,2015-04-04,1
1,2015-05-04,0
,我想发出这样的请求:
SELECT
(YEAR(date)) AS year_A,
(MONTH(date)) AS month_A,
(count(*)) AS number_A,
(count(*) WHERE state = 0) AS number_B
(count(*) WHERE state = 1) AS number_C
FROM A_transaction GROUP BY year_A, month_A
得到这样的东西
year_A,month_A,number_A,number_B,number_C
2015,04,2,1,1
但这不起作用。我认为问题出在WHERE子句
答案 0 :(得分:4)
您需要使用条件聚合编写查询(即只有在条件为true的情况下conda remove postgresql; sudo apt install postgresql
)。这将为您提供所需的结果:
COUNT
请注意,您不需要将表达式括在括号中。它们只会使您的查询难以阅读。
还要注意,标准的MySQL日期格式为SELECT YEAR(date) AS year_A,
MONTH(date) AS month_A,
count(*) AS number_A,
count(CASE WHEN state = 0 THEN 1 END) AS number_B,
count(CASE WHEN state = 1 THEN 1 END) AS number_C
FROM A_transaction
GROUP BY year_A, month_A
,这意味着表中的两个示例日期实际上在不同的月份,查询的输出为
YYYY-MM-DD
如果您的日期采用year_A month_A number_A number_B number_C
2015 4 1 0 1
2015 5 1 1 0
格式,则需要使用YYYY-DD-MM
进行转换,例如
STR_TO_DATE
答案 1 :(得分:1)
MySQL使获取这样的聚合列变得非常容易,因为它会评估python3.6 ./main.py
exist
Traceback (most recent call last):
File "./main.py", line 26, in <module>
start = StartUp()
TypeError: 'str' object is not callable
到state = 0
(0
)或false
(1
)。
因此,您不需要true
,就可以这样:
CASE..WHEN