如何使用按月,名称和数量分组来创建SQL Server查询?是否可以按字段和列值分组?在下面的示例中,我也需要将“猫”和“狗”归为“动物类别”,但是其他人可以与示例类似。
表格:
我的结果:
我做了什么:
SELECT
CONVERT(CHAR(8), Date, 112) AS 'Date',
Product.Type AS 'Type',
COUNT(DISTINCT Product.Id) AS 'Count',
Product.Operation AS 'Operation'
FROM
Product
GROUP BY
Product.Type, Product.Operation, CONVERT(CHAR(8), Product.Date, 112)
ORDER BY
Product.Type
有帮助吗?
答案 0 :(得分:0)
您能否详细说明一下“名称”字段以及提交的数量。
假设:名称字段=>类型和数量=>计数
可能的解决方案是:
SELECT Month([Date]), [Name]=type, Quantity=count(*)
FROM Product
GROUP BY Month([Date]), type
答案 1 :(得分:0)
类似的东西:
SELECT
convert(char(8), [Date], 112) as 'Date'
, case when P.[Type] in ('Cat', 'Dog') then 'Animal' else P.[Type] end AS 'Type'
, COUNT(DISTINCT P.Id) AS 'Count'
, P.Operation AS 'Operation'
FROM dbo.Product P
GROUP BY case when P.[Type] in ('Cat', 'Dog') then 'Animal' else P.[Type] end, P.Operation, Convert(char(8), [P.Date], 112)
ORDER BY case when P.[Type] in ('Cat', 'Dog') then 'Animal' else P.[Type] end