日期:2014-05-18  浏览次数:20392 次

统计问题,请高手帮忙,非常谢谢!
问题描述如下:假如有一个表shiyan
id               a                   b               c                 d                     e
1 1 3 4 6 NULL
2 2 3 4 NULL NULL
3 1 2 3 NULL NULL
4 2 6 NULL NULL NULL
5 2 3 4 5 NULL
6 2 3 5 NULL NULL
7 1 2 3 4 6
8 1 3 4 5 6
9 1 NULL NULL NULL NULL
要求统计出如下结果:
1   3   4   3
1   3   6   3
1   4   6   3
2   3   4   3
3   4   6   3
具体的描述是:以1   3   4   为例,在id=1的时候有,所以计数为1,id=7的时候也包含1   3   4,所以计数再加一,此时计数为2,在id=8的时候也包含1   3   4,所以计数再加1,此时的计数总数为3,也就是说,只要某一行里面包含1   3   4,计数就加1,不管顺序如何,只要某一行同时包含1   3   4这三个数,(不管他们的顺序是1   3   4还是1   4   3,还是4   3   1)它的计数就加一,最后要求显示出计数大于等于3的,也就是
1   3   4   3
1   3   6   3
1   4   6   3
2   3   4   3
3   4   6   3
请高手帮忙解决一下,用sql语句实现。
小弟我非常感激!


------解决方案--------------------
--呵呵,又是我
declare @shiyan1 table(id int, a int, b int,c int, d int, e int)
insert @shiyan1 select 1,1, 3,4, 6, NULL
union all select 2,2, 3,4, NULL, NULL
union all select 3,1, 2,3, NULL, NULL
union all select 4,2, 6,NULL, NULL, NULL
union all select 5,2, 3,4, 5, NULL
union all select 6,2, 3,5, NULL, NULL
union all select 7,1, 2,3, 4, 6
union all select 8,1, 3,4, 5, 6
union all select 9,1,NULL, NULL, NULL,NULL

declare @shiyan2 table(id int, a int, b int,c int)
insert @shiyan2 select 1,1 , 3,4
union all select 2,1 , 3,6
union all select 3,1, 4,6
union all select 4,2 , 3,4
union all select 5,3 , 4,6

--select * from @shiyan1
--select * from @shiyan2

select *,
(select count(*) from @shiyan1 where (t.a=a or t.a=b or t.a=c or t.a=d or t.a=e) and
(t.b=a or t.b=b or t.b=c or t.b=d or t.b=e) and
(t.c=a or t.c=b or t.c=c or t.c=d or t.c=e)
) 个数
from @shiyan2 t

--结果
id a b c 个数
----------- ----------- ----------- ----------- -----------
1 1 3 4 3
2 1 3 6 3
3 1 4 6 3
4 2 3 4 3
5 3 4 6 3

(所影响的行数为 5 行)

------解决方案--------------------
create table A(id int, a int, b int, c int, d int, e int)
insert A select 1, 1, 3, 4, 6, NULL
union all select 2, 2, 3, 4, NULL, NULL
union all select 3, 1, 2, 3, NULL, NULL
union all select 4, 2, 6, NULL, NULL, NULL
union all select 5, 2, 3, 4, 5, NULL
union all select 6, 2, 3, 5, NULL, NULL
union all select 7, 1, 2, 3, 4, 6
union all select 8, 1, 3, 4, 5, 6
union all select 9, 1, NULL, NULL, NULL, NULL

create table B(id int, a int, b int, c int)
insert B select 1, 1, 3, 4
union all select 2, 1, 3, 6