sql-server - 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 |
解决方案
首先你得到每个 ProductNR 的最短日期然后你按月分组
select count (distinct ProductNR) AS Count
from
(
select ProductNR, Date = min(Date)
from Products
group by ProductNR
) d
group by MONTH(Date)
推荐阅读
- xtext - Xtext 空格感知语法不能 Lex BEGIN 和 END
- vast - Inmobi Instream AD 请求 400 错误请求
- ios - 如何在模拟器中通过 Swift 5 检测外部麦克风
- javascript - js - 为什么在函数外使用时等待不抛出错误
- javascript - 我应该为 SocketIO 创建一个特定的路由吗?
- mysql - 无法使用 NodeRed 函数从 MySQL 获得响应
- r - 如何绘制拟合线?
- java - Spring Boot 覆盖通配符请求映射
- amazon-web-services - AWS - 使用 SecureTransport 设置策略后权限被拒绝:false
- apache - 带有范围列表的 Apache 表达式“-ipmatch”