如何返回所有记录ID,它们也是T-SQL中分组的一部分
我有一个垂直格式的数据集,每个AppId有不同数量的属性。我当前按属性和值分组以确定最大AppId。使用“比例”中不包含的Where属性忽略组中的比例属性。我还想知道分组中还包括哪些其他AppId值 下面是一个示例,说明了数据在源表中的结构,然后是如果数据被展平后的外观。接下来,是一个查询,它将为每个唯一分组提供最大AppId以及输出外观。如何还返回属于分组的其他AppId值 源表:如何返回所有记录ID,它们也是T-SQL中分组的一部分,sql,sql-server,tsql,group-by,Sql,Sql Server,Tsql,Group By,我有一个垂直格式的数据集,每个AppId有不同数量的属性。我当前按属性和值分组以确定最大AppId。使用“比例”中不包含的Where属性忽略组中的比例属性。我还想知道分组中还包括哪些其他AppId值 下面是一个示例,说明了数据在源表中的结构,然后是如果数据被展平后的外观。接下来,是一个查询,它将为每个唯一分组提供最大AppId以及输出外观。如何还返回属于分组的其他AppId值 源表: +--------+-------+-----------+------------+ | PartId | A
+--------+-------+-----------+------------+
| PartId | AppId | Attribute | Value |
+--------+-------+-----------+------------+
| ABC | ABC_1 | Color | Red |
| ABC | ABC_1 | Shape | Square |
| ABC | ABC_1 | Material | Plastic |
| ABC | ABC_1 | Scale | Celsius |
| ABC | ABC_2 | Color | RED |
| ABC | ABC_2 | Shape | Square |
| ABC | ABC_2 | Material | Plastic |
| ABC | ABC_2 | Scale | Fahrenheit |
| ABC | ABC_3 | Color | Red |
| ABC | ABC_4 | Color | Red |
| ABC | ABC_5 | Color | Green |
| ABC | ABC_5 | Shape | Round |
+--------+-------+-----------+------------+
旋转表示法:
+--------+-------+-------+--------+----------+------------+
| PartId | AppId | Color | Shape | Material | Scale |
+--------+-------+-------+--------+----------+------------+
| ABC | ABC_1 | Red | Square | Plastic | Celsius |
| ABC | ABC_2 | Red | Square | Plastic | Fahrenheit |
| ABC | ABC_3 | Red | | | |
| ABC | ABC_4 | Red | | | |
| ABC | ABC_5 | Green | Round | | |
+--------+-------+-------+--------+----------+------------+
获取最大AppId的查询
Select Distinct Max(AppId) As GroupAppId
From VerticleData
Where Attribute not in ('Scale')
Group By Attribute, Value
返回:
+------------+
| GroupAppId |
+------------+
| ABC_2 |
| ABC_4 |
| ABC_5 |
+------------+
期望输出:
+------------+-------+
| GroupAppId | AppId |
+------------+-------+
| ABC_2 | ABC_1 |
| ABC_2 | ABC_2 |
| ABC_4 | ABC_3 |
| ABC_4 | ABC_4 |
| ABC_5 | ABC_5 |
+------------+-------+
下面是一种使用窗口函数的方法:
select distinct GroupAppId, AppId
from (select vd.*, max(AppId) over (partition by Attribute, Value) as GroupAppId
from VerticleData vd
Where Attribute not in ('Scale')
) vd
Where Attribute not in ('Scale');
编辑:
我想你可能想要这样的东西:
select max( GroupAppId), AppId
from (select vd.*, max(AppId) over (partition by Attribute, Value) as GroupAppId
from VerticleData vd
Where Attribute not in ('Scale')
) vd
where Attribute not in ('Scale')
group by AppId;
但我不明白为什么App_4与App_1和App_2不匹配
由lmingle编辑II:
工作查询:
Select distinct min(GroupAppID), AppId
From
(
select distinct GroupAppId, AppId
from (select vd.*, max(AppId) over (partition by Attribute, Value) as GroupAppId
from VerticleData vd
Where Attribute not in ('Scale')
) vd
Where Attribute not in ('Scale')
) as a
Group By AppId
我将为GroupAppId ABC_4返回额外的AppId值ABC_1和ABC_2。为什么你会选择ABC_2而不是ABC_4?ABC_4的旋转表示法意外地填充了形状和材料-我更正了它。对于分组,ABC_3和ABC_4的属性颜色仅为红色。而ABC_1和ABC_2有颜色、形状和材料。属性比例被忽略。我猜答案中的两个查询中的一个会起作用。我能够添加一些更为复杂的逻辑来获得具有所需结果的minAppId。不是最漂亮的查询,但结果是我想要的。