2011-03-30 51 views
0

我有3列的表,SQL Server 2008中SQL Server查詢組由項目

item, count , date 

我想作爲與具有格式2011 日期colums選擇每個項目的總數爲當天查詢-03-30 09:00:00.000

select 
    date,item, sum(count) as total 
from 
    table1 
group by 
    date,item 

編輯:

select item, dateadd(day,datediff(day,0,date),0) as dateInserted, sum(count) 
as total from Table1 group by item, dateadd(day,datediff(day,0,date),0) order by 1 

第一選擇換貨政... rns總計但按日期時間分組而不是日期...然後第二個返回總計正確,但我發現一些項目出現兩次相同的日期,但不同的總數

+2

「客戶羣」進入此處何處? – Blorgbeard 2011-03-30 15:46:58

+0

此查詢有何結果? – Bastardo 2011-03-30 15:48:40

+0

您是否需要添加where子句以將行限制爲「當前日期」? – Beth 2011-03-30 15:53:55

回答

1

聽起來像你正在尋找'當前日'的結果?

select item, dateadd(day, datediff(day, 0, date), 0) as dateInserted, 
     sum(count) as total 
from Table1 
WHERE  
    dateadd(day, datediff(day, 0, [date]), 0) = 
    dateadd(day, datediff(day, 0, getdate()), 0) 
group by 
    item, dateadd(day, datediff(day, 0, date), 0) 
order by 1 

如果您使用SQL Server 2008中,使用DATE數據類型。

select item, 
     CAST([date] as DATE)) as dateInserted, 
     sum(count) as total 
from Table1 
WHERE  
    CAST([date] as DATE)) = CAST(getdate() as DATE) 
group by 
    item, CAST([date] as DATE)) 
order by 1 
+0

是在正確的軌道上謝謝...插入或凡datedadd(day ... getdate()-1)前一天的結果。欣賞它。 – vbNewbie 2011-03-30 15:59:16

+0

爲什麼我仍然得到總計分組兩次,像項目20出現兩次2011-03-30日期但有2個不同的總計 – vbNewbie 2011-03-30 16:57:08

+0

@vbNewbie:什麼樣的數據類型是列'項目? – 2011-03-30 17:06:05