在SQL Server中按多个参数分组

时间:2019-03-05 01:44:20

标签: sql sql-server

我有一个具有以下结构的表:

id | timestamp | barcode

时间戳是datetime列,条形码是完整的条形码,我只需要前9位即可。

我每天需要每个班次的物品计数。

Day是转换为日期的时间戳。

移位如下:

  • 班次1是从06:00:00到14:29:59
  • 第二班从14:30:00到22:59:59
  • 班次3从23:00:00到05:59:59

项目编号仅为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)

1 个答案:

答案 0 :(得分:1)

这基本上是具有一堆计算列的聚合。这是一种方法:

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