sql server逐项查询

时间:2011-03-30 15:36:22

标签: sql-server

我有一个包含3列的表,sql server 2008

item, count , date

我想要一个查询,用于选择当前日期每件商品的总计数 日期列的格式为2011-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

第一个选择返回总计但按日期时间而不是日期分组...然后第二个返回总计正确但我发现一些项目出现两次具有相同的日期但不同的总数

1 个答案:

答案 0 :(得分: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