每小时每种类型的SQL计数

时间:2012-12-06 09:09:35

标签: sql sql-server count

想要计算一小时内记录的类型数量。

我可以使用此代码计算类型的数量:

SELECT count (left (Barcode,9)) as T_Count, left (Barcode,9) as T
FROM table
group by left (Barcode,9)

并且可以使用此代码(包括所有类型)计算每小时的项目数:

SELECT Year, Month, Day, Hour, COUNT(T) AS "Items per Hour"
FROM
(
SELECT DATEPART(YEAR,timestamp) Year, DATEPART(MONTH,timestamp) Month,
DATEPART(DAY,timestamp) Day, DATEPART(HOUR, timestamp) Hour, left (Barcode,9) as T
FROM table
) temp
group by Year, Month, Day, Hour
order by Year desc, Month desc, Day desc

但是不知道如何计算每小时每种类型的物品数量 - 这意味着一小时内将有超过1个物品 - 根据类型的数量......

1 个答案:

答案 0 :(得分:0)

SELECT 
    Year, Month, Day, Hour, 
    COUNT(T) AS "Items per Hour", 
    count (distinct T) as "Types per Hour"
FROM 
    ( SELECT DATEPART(YEAR,timestamp) Year, DATEPART(MONTH,timestamp) Month, DATEPART(DAY,timestamp) Day, DATEPART(HOUR, timestamp) Hour, left (Barcode,9) as T FROM [JCI_Trim].[dbo].[T6_Trim] ) temp 
group by Year, Month, Day, Hour 
order by Year desc, Month desc, Day desc