[英]Grouping by multiple parameters in SQL Server
我有一个具有以下结构的表:
id | timestamp | barcode
时间戳是一个datetime
列,条形码是完整的条形码,我只需要前9位数字。
我需要每天每个班次的项目计数。
Day是转换为日期的时间戳。
移位如下:
项目编号就在left(barcode, 9)
。
基本上我需要一个结果为:
date | shift | item_number | count
-----------+-------+-------------+------
21.02.2019 | 1 | 298193879 | 32
我设法按日期和项目编号将它们分组,如下所示,但未返回期望的结果。
select
cast([timestamp] as date), left(barcode, 9) as itemnumber, count(*)
from
tablename
group by
cast([timestamp] as date), left(barcode, 9)
这基本上是具有一堆计算列的聚合。 这是一种方法:
select cast(timestamp as date) as date,
(case when convert(time, timestamp) >= '06:00:00' and
convert(time, timestamp) < '14:30:00'
then 1
when convert(time, timestamp) >= '14:30:00' and
convert(time, timestamp) < '23:00:00'
then 2
else 3
end) as shift,
left(barcode, 9) as item_number,
count(*)
from t
group by cast(timestamp as date),
(case when convert(time, timestamp) >= '06:00:00' and
convert(time, timestamp) < '14:30:00'
then 1
when convert(time, timestamp) >= '14:30:00' and
convert(time, timestamp) < '23:00:00'
then 2
else 3
end),
left(barcode, 9)
order by date, shift, item_number;
如果使用cross apply
来定义变量,则编写起来更简单(并且更不容易出错):
select v.date, v.shift, v.item_number,
count(*)
from t cross apply
(values (cast(timestamp as date),
(case when convert(time, timestamp) >= '06:00:00' and
convert(time, timestamp) < '14:30:00'
then 1
when convert(time, timestamp) >= '14:30:00' and
convert(time, timestamp) < '23:00:00'
then 2
else 3
end),
left(barcode, 9)
)
) v(date, shift, item_number)
group v.date, v.shift, v.item_number
order by date, shift, item_number
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.