首页 > 解决方案 > SQL 按具有多个唯一值的多列分组,用于分组列

问题描述

我正在寻找一种按两列分组的方法,其中第一个分组列对于第二个分组列具有多个唯一值。下面是带有示例数据的示例表。

CREATE TABLE [dbo].[MyTable](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Type] [varchar](20) NOT NULL,
    [UnitOfMeasure] [varchar](20) NULL,
 CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
) ON [PRimary]
) ON [PRimary];

INSERT INTO [MyTable] (Type, UnitOfMeasure)
VALUES ('height', 'cm')
,   ('distance', 'km')
,   ('weight', 'kg')
,   ('Glucose', 'mg/dL')
,   ('weight', 'kg')
,   ('Duration', 'hours')
,   ('Glucose', 'mg/dL')
,   ('Glucose', 'mg/dL')
,   ('height', 'cm')
,   ('Allergy', 'kUnits/L')
,   ('Volume', 'mL')
,   ('height', 'inch')
,   ('height', 'cm')
,   ('Chloride', 'mmol/L')
,   ('Volume', 'cup')
,   ('distance', 'km')
,   ('Volume', 'cup')
,   ('Duration', 'hours')
,   ('Chloride', 'mmol/L')
,   ('Duration', 'minutes');

期望的输出如下。

Type        UnitOfMeasure
Duration    hours
Duration    minutes
height      cm
height      inch
Volume      cup
Volume      mL

此输出包括 Duration,因为它有两个度量单位。但是,它不包括重量,也不包括氯化物,因为它只有一个计量单位。

标签: sql-server

解决方案


您可以使用 CTE 获得 a DISTINCT COUNT,然后使用 aEXISTS与进一步DISTINCT。不过,我希望这会有点贵,理想情况下,您可能想要解决您拥有的那些重复行。

WITH Counts AS(
    SELECT [Type],
           COUNT(DISTINCT UnitOfMeasure) AS DistinctMeasures
    FROM dbo.MyTable
    GROUP BY [Type])
SELECT DISTINCT
       [Type],
       UnitOfMeasure
FROM dbo.MyTable MT
WHERE EXISTS (SELECT 1
              FROM Counts C
              WHERE C.[Type] = MT.[Type]
                AND C.DistinctMeasures > 1);

推荐阅读