【问题标题】:MSSQL retrieve a value 1 time in a GROUP BYMSSQL 在 GROUP BY 中检索值 1 次
【发布时间】:2018-07-11 12:47:08
【问题描述】:

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

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   |

【问题讨论】:

  • 它给了我同样的结果
  • 第二个查询统计每组中不同值的个数,也就是说GROUP BY的优先级高于COUNT()中的DISTINCT关键字.您能解释一下业务需求吗?

标签: sql-server group-by distinct


【解决方案1】:

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

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

【讨论】:

  • 我想知道,如果我的 select 语句中有 2 个“计数”语句,第二个计数应该只检索每个月的所有内容,而不需要“min =(date)”怎么办完成了吗?
【解决方案2】:

您可以添加子选择并仅使用日期=产品的最小日期的行

  select count (distinct ProductNR) AS Count
    from Products as Products
    where date =(select  min(date) 
                   from Products as MinProd 
                  where MinProd.ProductNR =Products.ProductNR 
                 ) 
    group by MONTH(date)

只有在最小日期不同时才有效 beater 将使用标识列并在子查询中选择前 1(此返回始终只有一行)

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

 INSERT INTO Products2 (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) AS Count
from Products as Products
where date =(select  min(date) 
               from Products as MinProd 
              where MinProd.ProductNR =Products.ProductNR 
             ) 
group by MONTH(date)

【讨论】:

    【解决方案3】:

    我认为你想要实现的是这个

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

    【讨论】:

    • 当你有group by ProductNRcount (distinct ProductNR) 总会给你1
    • @Squirrel 并选择按 ProductNR 和最小日期分组会给你多个吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 2010-10-21
    • 2018-10-26
    • 2020-01-01
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多