我有一个表格,其中有多种类型的列,例如type1,2,3和4
我需要一个sql查询,我需要根据日期/小时数来计算每种类型的记录,即26/01/2010 00
,26/01/2010 01 am
等等
非常感谢任何帮助。
DATE TYPE1_RECORDS TYPE2_RECORDS TYPE3_RECORDS TYPE4_RECORDS
26/01/2010 00 2 1 4 3
26/01/2010 01 8 7 2 7
26/01/2010 02 0 1 6 1
26/01/2010 03 0 4 0 3
26/01/2010 04 1 2 9 9
26/01/2010 05 3 3 2 0
26/01/2010 06 6 7 6 4
答案 0 :(得分:0)
您可以使用分析函数计数(*):
select a.*,
count(*) over(partition by <first group of columns>) ,
count(*) over(partition by <second group of columns>) ,
....
from <table> a
答案 1 :(得分:0)
根据您对Rusty的回答的评论,您希望按日期和小时记录一条记录,因此请使用TO_CHAR获取此类字符串和组。您可以使用条件聚合获得计数。
select
to_char(mydate, 'dd/mm/yyyy hh24') as date_and_hour,
count(case when type = 1 then 1 end) as type1_count,
count(case when type = 2 then 1 end) as type2_count,
count(case when type = 3 then 1 end) as type3_count,
count(case when type = 4 then 1 end) as type4_count
from mytable
group by to_char(mydate, 'dd/mm/yyyy hh24')
order by max(mydate), to_char(mydate, 'dd/mm/yyyy hh24');
我使用max(mydate)进行排序,这当然是date_and_hour的一个日期,也可以使用min(mydate)或将mydate添加到GROUP BY子句然后直接使用它。我们只想按日期排序,而不是按字符串排序(我们将首先获得所有第一个Januaries)。