在名为“Transactions”的postgres表中,我试图计算每个月的J型交易数量。以下是我的询问。
select to_char("Date", 'Mon/YYYY') as "Date",
sum(case when l_part LIKE 'J%' then count end) as "IDs"
from (
select left("Type",4)as l_part, count(*),"Date" from
"Transactions" group by "Date",l_part
) p group by "Date"
order by min("Date");
但是,我的查询出现了一些问题。
1)计算的数量累积,因此每个月的计数也会增加以前所有月份的总数。但是,我只想单独计算每月。
2)使用此查询,我的输出会重复几个月(即2015年5月我有3行,2行为空,1行有实际计数)
任何见解都将不胜感激。
答案 0 :(得分:1)
我认为没有子查询这样做更简单:
SELECT date_trunc('month', "Date"), count(*)
FROM "Transactions"
WHERE "Type" LIKE 'J%'
GROUP BY date_trunc('month', "Date");
<强>编辑:强>
date_trunc('month', ...)
函数将日期截断为其当月的第一天。 '2015-May-26'
和'2015-May-09'
都变为'2015-May-01'
等。
我使用此功能代替to_char
,因为它是我的习惯,因为text
分组可能比date
分组慢。当然,这取决于"Transactions"
表的大小。
答案 1 :(得分:1)
我认为你根本不需要这个子选择。试试这个:
SELECT
to_char("Date", 'Mon/YYYY') AS d,
count(*) AS "IDs"
FROM "Transactions"
WHERE "Type" LIKE 'J%'
GROUP BY d