如何按日期创建SQL多计数查询?

时间:2017-06-07 05:52:42

标签: sql postgresql

我有一个按部门选择计数的查询。

select department, count(*) group by department

这返回两列数据结果。我想知道是否选择cout,今天计算并按本月相同的查询计算。

Department  Total  Today  ThisMonth
AAA         40     8      23
BBB         20     6      11

4 个答案:

答案 0 :(得分:1)

试试这个

0

答案 1 :(得分:0)

@SimarjeetSingh已经回答了这个问题。

除了与datecolumn的比较只发生在datepart上,GETDATE()用它重新调整时间。

select department, count(*) as Total,
sum(case when cast(datecolumn as date)= cast(GETDATE() as date)  then 1 else 0 end) as Today,
sum(case when month(datecolumn) =month(GETDATE()) and year(datecolumn) = year(GETDATE()) then 1 else 0 end) as ThisMonth
from YourTable
group by department

答案 2 :(得分:0)

datecoulmn与getdate()的比较应该是MMYYYY来获得ThisMonth总数。

select department,count(*) as Total,
sum(case when convert(varchar,datecolumn,106)= convert(varchar,GETDATE(),106) then 1 else 0 end) as Today,
sum(case when cast(month(datecolumn) as varchar) + cast(year(datecolumn) as varchar)  = cast(year(GETDATE()) as varchar) + cast(year(GETDATE()) as varchar)  then 1 else 0 end) as ThisMonth
from YourTable
group by department 

答案 3 :(得分:0)

select
  department,
  count(*) as total,
  count(*) filter (where datecolumn = current_date) as count_for_today,
  count(*) filter (where date_trunc('month', datecolumn) = date_trunc('month', current_date)) as count_for_month
from
  your_table
group by
  department

FILTER clause
date_trunc function