我在表格中有这3个字段。
trans_date | transaction_type | CLIENT_ID
我需要的是每个日期的transaction_types条目计数。例如,
日期:2015年7月7日总计数:6 transaction_type 1计数:3,
transaction_type 2 count:1,transaction_type 3 count:2 etc ....
我对每个日期分组的所有日期都需要这个。
这是我当前的查询,
SELECT count(id) as total_count,
(select count(id) where transaction_type=1) as type1_count,
(select count(id) where transaction_type=2) as type2_count,
(select count(id) where transaction_type=3) as type3_count
FROM tblTransactions
where client_id=1
GROUP BY date(trans_date/1000, 'unixepoch')
这会返回不匹配的奇怪数字。我做错了什么?
答案 0 :(得分:2)
您获得奇怪值的原因是您的子查询未按日期过滤,因此您将获得每种交易类型的总计数。你需要的是一个相关的子查询,它将从外部查询获得一个参数:
SELECT count(id) as total_count,
(select count(id) where transaction_type=1 and trans_date=t.trans_date) as type1_count,
(select count(id) where transaction_type=2 and trans_date=t.trans_date) as type2_count,
(select count(id) where transaction_type=3 and trans_date=t.trans_date) as type3_count
FROM tblTransactions t
where client_id=1
GROUP BY date(trans_date/1000, 'unixepoch')
答案 1 :(得分:1)
您可以使用sum函数而不是子查询
select date(trans_date/1000, 'unixepoch') d,
sum(case when transaction_type = 1 then 1 else 0 end) type1_count,
sum(case when transaction_type = 2 then 1 else 0 end) type2_count,
sum(case when transaction_type = 3 then 1 else 0 end) type3_count
from tblTransactions
where client_id=1
group by d