SQL中子查询中列的求和运算

时间:2018-09-06 10:07:19

标签: sql postgresql

可能只是我的方法不好。我的数据库中有以下架构:

work_instances_table(wk_id, wk_occurance_id, start_time, end_time)
time_table(time_id, hour, minute, period)

多个work_occurances可以小于一个wk_id。例如:

wk_id | wk_occurance_id | start_time | end_time

1     | wk_01           | 111        | 111
2     | wk_02           | 345        | 345
1     | wk_03           | 654        | 655
1     | wk_04           | 132        | 132
2     | wk_05           | 051        | 053

,在time_table中,我们可以将start_timeend_timetime_id连接起来。

假设我想得到

两次两次之间开始的所有工作发生的次数,例如凌晨0到3。

我尝试过

select w1.wk_id,
      COUNT(w1.wk_occurance_id) as total_wk_occurances 
      from work_instances w1 
      inner join 
          time_dimension td1 on w1.start_time = td1.time_id  
      where 
          (td1.hour between 0 and 3  and td1.minute between 0 and 59 and td1.period = 'AM')
      group by w1.wk_id;

这给了我

    1  |  2
    2  |  1

1次出现2次,而2次出现1次。

现在如何总结?

表示如何扩展查询以说total 2 works and 3 occurrences ran?

请解释并扩展最初使用的查询本身,方法可能是将其编写为子查询。

2 个答案:

答案 0 :(得分:1)

使用子查询和聚合

  select count(wk_id) as numberofwork,
  sum(total_wk_occurances) as occurrences   from   
   (  select w1.wk_id,
      COUNT(w1.wk_occurance_id) as total_wk_occurances 
      from work_instances w1 
      inner join 
          time_dimension td1 on w1.start_time = td1.time_id  
      where 
          (td1.hour between 0 and 3  and td1.minute between 0 and 59 and td1.period = 'AM')
      group by w1.wk_id
   ) as  t1

你可以用下面的方法写同样的东西

with cte as
(
select w1.wk_id,
          COUNT(w1.wk_occurance_id) as total_wk_occurances 
          from work_instances w1 
          inner join 
              time_dimension td1 on w1.start_time = td1.time_id  
          where 
              (td1.hour between 0 and 3  and td1.minute between 0 and 59 and td1.period = 'AM')
          group by w1.wk_id
)  select count(wk_id),sum(total_wk_occurances) as occurrences from cte

答案 1 :(得分:1)

我认为这个更简单的解决方案应该可以工作,请注意,如果您只对全职工作感兴趣,那么有必要查看分钟栏。

id,sort,enabled,font,store
1,1,1,Adlib,0
2,2,1,Arial,0
3,3,1,"Arial Bold",0
4,4,1,"Arial Black",0
----------
----------
40,40,1,Harlow,0
41,41,1,"Hobby Headline",0
42,42,1,"Hobby Horse",0
----------
----------
85,85,1,"Wild West",0
86,86,1,"Zap Chance",0
87,87,1,Helvetica,0

在问题中它说的是0到3 AM,因此如果您要这样做,则将where子句更改为与此类似的内容

SELECT COUNT(distinct w.wk_id), COUNT(distinct w.wk_occurance_id)
FROM work_instances_table w
JOIN time_table t ON t.time_id = w.start_time 
WHERE t.hour >= 0 AND t.hour <= 3