2017-10-28 112 views
0

我有這個疑問:兩列的按ID和日期分組,但每個組的日期?

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

感謝。

回答

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); 

,但似乎沒有必要。

請注意,我用一個in替換了or表達式。而且,我已經寫出了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); 
+0

我有,但我需要知道valueU(70)具有「2017年10月28日3:00:00.000',而L值(13)爲'2017-10-28 4:00:00.000'。我在問題中包含了所需的結果集 – rbhat

0
SELECT DISTINCT Id, 
       SUM(CounterL) OVER(PARTITION BY ID, CAST(InsertDate AS DATE)) AS [ColumnL], 
       SUM(CounterU) OVER(PARTITION BY ID, CAST(InsertDate AS DATE)) As [ColumnU], 
       CAST(InsertDate AS DATE) [Date],    
       DATEADD(HOUR, 3-DATEPART(HOUR, InsertDate), InsertDate) AS [ValueU], 
       DATEADD(HOUR, 4-DATEPART(HOUR, InsertDate), InsertDate) AS [ValueL] 
FROM @values 
WHERE DATEPART(HH, INSERTDATE) IN (3,4)