如何聚合唯一字符串值或NULL

mje*_*ins 2 sql sql-server aggregate-functions

有没有办法聚合字符串值,如果它是唯一的或否则返回NULL.例如,给定表"STUFF":

Col_A | Col_B | Col_C | Col_D
    1 | Foo   | Bar   |     6
    2 | Foo   | NoBar |     0
    2 | Foo   | Foo   |     4
    1 | Foo   | Bar   |     6
Run Code Online (Sandbox Code Playgroud)

这样的SQL

SELECT SUM(COL_A), STR_AGG_FUNC(COL_B), STR_AGG_FUNC(COL_C),SUM(COL_D) FROM STUFF
Run Code Online (Sandbox Code Playgroud)

会回来:

Col_A | Col_B | Col_C | Col_D
    6 | Foo   | NULL  |    16
Run Code Online (Sandbox Code Playgroud)

scs*_*mon 6

您可以在这些列上使用max和case语句执行此操作.

select
   Col_A = sum(Col_A)
   ,Col_B = case when max(Col_B) = min(Col_B) then max(Col_B) else null end
   ,Col_C = case when max(Col_C) = min(Col_C) then max(Col_C) else null end
   ,Col_D = sum(Col_D)
From
   Stuff
Run Code Online (Sandbox Code Playgroud)