简体   繁体   English

在SQL Server中按两个参数分组

[英]Grouping by two parameters in SQL Server

I have a table with this structure: 我有一个具有这种结构的表:

id | timestamp | barcode

The timestamp is datetime and the barcode is a full barcode, from which I need only the first 9 digits. 时间戳是日期时间,条形码是完整条形码,我只需要前9位数字即可。

I need to get the count for each product for each day with one query. 我需要通过一个查询来获取每天每种产品的计数。

So I basically need a result like: 所以我基本上需要这样的结果:

date       | item number | count
-----------+-------------+--------
12.02.2019 | 827384950   | 32

Item number is left(barcode, 9) . left(barcode, 9)项目编号left(barcode, 9)

You can try below - using cast() to convert timestamp to date and then add that in group by 您可以尝试以下操作-使用cast()将时间戳转换为日期,然后将其添加到

select cast([timestamp] as date),left(barcode, 9) as itemnumber,count(*)
from tablename
group by cast([timestamp] as date),left(barcode, 9)

this query has better performance 该查询具有更好的性能

select date, itemnumber, count(*) from
(select cast([timestamp] as date) as date,left(barcode, 9) as itemnumber
from tablename) a
group by date,itemnumber

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM