1

感谢您的审阅。我迫切需要帮助,甚至无法明确以下问题...

使用 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值的记录,我想识别column2through的每个唯一排列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

等等。谢谢!

4

2 回答 2

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)
于 2013-07-02T13:49:16.830 回答
0

唔。如果您想手动完成,则应该使用带有多个键的 group by之类的东西。例如,对于案例 1,您应该执行以下操作:

select column1,column2,column3, column4, count(column5) group by column1,column2,column3, column4

这应该为 column1-column4 的每个唯一组合提供唯一记录。如果你想要不同,那么你可能需要做一些预处理。

如果您想要一个更灵活的方法,那么执行 group by 的存储过程可能是一种解决方案。

于 2013-07-02T13:38:29.303 回答