首页 > 解决方案 > MSSQL 在 GROUP BY 中检索值 1 次

问题描述

我有一个包含以下数据的表:

CREATE TABLE [dbo].[Products](
[ProductNR] [varchar](14) NULL,
[Location] [int] NULL,
[Date] [datetime] NULL
);

 INSERT INTO Products (ProductNR, Location, Date)
 VALUES 
 ('1234' ,1, '2016-01-17 12:30:50.010'),
 ('4567' ,1, '2016-03-17 12:30:50.010'),
 ('8978' ,1, '2016-04-17 12:30:50.010'),
 ('2578' ,1, '2016-05-17 12:30:50.010'),
 ('1234' ,2, '2016-06-17 12:30:50.010'),
 ('1234' ,3, '2016-07-17 12:30:50.010');

select count (distinct ProductNR)
from Products

结果:

|Count|
|  4  |

但是当我像下面这样使用 GROUP BY 语句时:

select count (distinct ProductNR) AS Count
from Products
group by MONTH(date)

结果:

|Count|
| 1   |
| 1   |
| 1   |
| 1   |
| 1   | 
| 1   |

总共是6,但我想在整个表/GROUP BY 语句中检索一次 ID,这意味着我只希望返回 4 行,其中计算每个 ID 的第一个注册日期。

期望的结果,其中 ProductNR 1234仅检索一次:

|Count|
| 1   |
| 1   |
| 1   |
| 1   |

标签: sql-servergroup-bydistinct

解决方案


首先你得到每个 ProductNR 的最短日期然后你按月分组

select  count (distinct ProductNR) AS Count
from
(
    select  ProductNR, Date = min(Date)
    from    Products
    group by ProductNR
) d
group by MONTH(Date)

推荐阅读