感谢您的审核。我迫切需要帮助,甚至在下面的问题上明确表示有困难......
使用SQL 2008我有一个设置了五列的表。
数据实际上看起来像这样:
column1 column2 column3 column4 column5
T1 N1 A1 L1 S1
T1 N2 A2 L2 S4
T1 N2 A3 L2 S2
T1 N2 A1 L2 S4
T2 N6 A3 L3 S2
T2 N7 A3 L3 S4
T2 N7 A3 L4 S4
...
对于具有相同column1
值的记录,我想确定column2
到column5
的每个唯一排列。
我想回答这样的问题:
案例1
存在多少条记录
column1 is the same value and
column2 is the same value and
column3 is the same value and
column4 is the same value and
column5 is different
然后
案例2
column1 is the same value and
column2 is the same value and
column3 is the same value and
column4 is different and
column5 is the same value
然后
案例3
column1 is the same value and
column2 is the same value and
column3 is the same value and
column4 is different and
column5 is different
等等。谢谢!
答案 0 :(得分:1)
您可以在一个查询中执行此操作,方法是在查询中设置所需排列的表格以及一些case
逻辑。
以下是三列的示例。
with t as (
select 'a' as a, 'b' as b, 'c' as c union all
select 'a', 'b', 'd' union all
select 'e', 'b', 'd'
),
perms as (
select 1 as col1, 1 as col2, 1 as col3 union all
select 1, 1, 0 union all
select 1, 0, 0 union all
select 0, 1, 1 union all
select 0, 1, 0 union all
select 0, 0, 1
)
select (case when p.col1 = 1 then a end) as col1,
(case when p.col2 = 1 then b end) as col2,
(case when p.col3 = 1 then c end) as col3,
count(*)
from t cross join
perms p
group by (case when p.col1 = 1 then a end),
(case when p.col2 = 1 then b end),
(case when p.col3 = 1 then c end)
答案 1 :(得分:0)
嗯。如果您想手动执行此操作,则应使用具有多个键的group by之类的操作。例如。对于案例1,您应该执行以下操作:
select column1,column2,column3, column4, count(column5) group by column1,column2,column3, column4
这应该为column1-column4的每个唯一组合提供唯一记录。如果你想要不同,那么你可能需要做一些预处理。
如果您想要更灵活,可能是执行分组的商店程序可能是一个解决方案。