[英]SQL query to return all columns of max date for group by but exclude records where a different column for that group is not null
[英]SQL Return a list of column names where the columns have different values across multiple records within a group
有人可以指出如何解决 SQL(SQL Server 2012)中的以下问题的正确方法吗?
在表 A 中,列出了多个组 (GID) 的对象 (OID)。 每个 object 都由一组给定的属性 (Col_A.. Col_F) 描述。
对于每个组,我想列出在该组的所有对象中具有不同值的那些属性。 空列表表示该组的所有对象具有相同的属性值。
给定:表 A 显示了 3 个组,其中具有可变数量的具有相同结构的对象。
GID | OID | 可乐 | Col_B | Col_C | 寒冷的 | 油菜 | Col_F |
---|---|---|---|---|---|---|---|
G1 | C1 | 33 | 2 | 不 | 绿色的 | 7 | 彼得 |
G1 | C2 | 33 | 2 | 不 | 绿色的 | 1 | 彼得 |
G1 | C3 | 33 | 2 | 是的 | 绿色的 | 1 | 彼得 |
G1 | C4 | 33 | 2 | 也许 | 绿色的 | 1 | 彼得 |
G1 | C5 | 33 | 2 | 不 | 绿色的 | 1 | 彼得 |
G2 | C1 | 33 | 2 | 不 | 蓝色的 | 1 | 玛丽 |
G2 | C2 | 33 | 1 | 不 | 蓝色的 | 2 | 玛丽 |
G2 | C3 | 34 | 2 | 不 | 蓝色的 | 1 | 玛丽 |
G3 | C1 | 33 | 9 | 不 | 蓝色的 | 1 | 本 |
G3 | C2 | 33 | 9 | 不 | 蓝色的 | 1 | 本 |
G3 | C3 | 33 | 9 | 不 | 蓝色的 | 1 | 本 |
结果集:
团体 | 差异 |
---|---|
G1 | Col_C, COL_E |
G2 | Col_A、Col_B、Col_E |
G3 | 空的 |
有任何想法吗? 谢谢你。
如果我理解正确:
select gid,
trim(leading ',' from
(case when min(col_a) <> max(col_a) then ',col_a' else '' end ||
case when min(col_b) <> max(col_b) then ',col_b' else '' end ||
case when min(col_c) <> max(col_c) then ',col_c' else '' end ||
case when min(col_d) <> max(col_d) then ',col_d' else '' end ||
case when min(col_e) <> max(col_e) then ',col_e' else '' end ||
case when min(col_f) <> max(col_f) then ',col_f' else '' end ||
) ) as exceptions
from t
group by gid;
两个注意事项:
NULL
s。 您没有指定如何处理它们。 以上只是忽略了NULL
值。在 SQL 服务器的最新版本中,最简单的写成:
select gid,
concat_ws(',',
case when min(col_a) <> max(col_a) then 'col_a' end,
case when min(col_b) <> max(col_b) then 'col_b' end,
case when min(col_c) <> max(col_c) then 'col_c' end,
case when min(col_d) <> max(col_d) then 'col_d' end,
case when min(col_e) <> max(col_e) then 'col_e' end,
case when min(col_f) <> max(col_f) then 'col_f' end
) as exceptions
from t
group by gid;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.