sql-server - 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,因为它有两个度量单位。但是,它不包括重量,也不包括氯化物,因为它只有一个计量单位。
解决方案
您可以使用 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);
推荐阅读
- python - Pygame 中的 Screen.Fill() 不会改变屏幕
- php - Laravel API 身份验证 - 护照令牌
- git - 提交增量之间的差异,而不是自己提交
- java - 骆驼卡夫卡路线不熬夜
- rust - `cargo clippy` 仅在第一次运行时产生输出
- android - 片段点击后显示条形图
- html - 如何缩放具有最小和最大宽度的 flexbox 元素?
- apache-spark - 如何在 Kerberized 集群上的 Spark 流应用程序的最大生命周期过后重新颁发委托令牌
- ruby-on-rails - 如何在控制器中构建查询但只进行一次数据库调用
- javascript - 如何使用 onclick 运行 Javascript 函数