按ID和日期分组,但每组的日期?

时间:2017-10-28 14:18:31

标签: sql sql-server tsql

我有这个问题:

declare @values table
(
    Id int,
    Dept varchar(1),
    CounterL int,
    CounterU int,
    InsertDate datetime
)
insert into @values 
select 1, 'L', 5, null, '2017-10-28 4:00:00.000'
union
select 1, 'L', 8, null, '2017-10-28 4:00:00.000'
union
select 1, 'U', null, 30, '2017-10-28 3:00:00.000'
union
select 1, 'U', null, 40, '2017-10-28 3:00:00.000'


select id, sum(counterl), sum(counteru) from @values
where (datepart(hh, insertdate) = 4 or datepart(hh, insertdate) = 3)
group by id, cast(InsertDate as date)

以下内容返回两列的总和,但我希望能够包含每个列的日期。

示例看起来像这样:

id  ColumnL, ColumnU,  Date         ValueU                    ValueL
1   13       70        2017-10-28   '2017-10-28 3:00:00.000'  '2017-10-28 4:00:00.000'

一天总有两个小时,HR 3或4。

感谢。

2 个答案:

答案 0 :(得分:1)

这不够吗?

select id, sum(counterl), sum(counteru), cast(InsertDate as date) as dte
from @values v
where datepart(hour, insertdate) in (3, 4)
group by id, cast(InsertDate as date);

我的意思是,您还可以添加小时:

select id, sum(counterl), sum(counteru), cast(InsertDate as date) as dte,
       dateadd(hour, 3, cast(InsertDate as date)),
       dateadd(hour, 4, cast(InsertDate as date))
from @values v
where datepart(hour, insertdate) in (3, 4)
group by id, cast(InsertDate as date);

但这似乎没必要。

请注意,我将or表达式替换为单个in。而且,我已经拼出hour,因此代码更容易阅读。

编辑:

根据您的评论,您需要条件聚合:

select id, sum(counterl), sum(counteru), cast(InsertDate as date) as dte,
       min(case when dept = 'L' then InsertDate end) as l_insertdate,
       min(case when dept = 'U' then InsertDate end) as u_insertdate
from @values v
where datepart(hour, insertdate) in (3, 4)
group by id, cast(InsertDate as date);

答案 1 :(得分:0)

visited_links