34,576
社区成员
发帖
与我相关
我的任务
分享
--> 测试数据:#
if object_id('tempdb.dbo.#') is not null drop table #
create table #(select_id int, row_id int, val varchar(8))
insert into #
-- 第一行 a1 第二行 a2 b2
select 1, 1, 'a1' union all
select 1, 2, 'a2' union all
select 1, 2, 'b2' union all
-- 第一行 a1 第二行 a2 b2 第三行 a3
select 2, 1, 'a1' union all
select 2, 2, 'a2' union all
select 2, 2, 'b2' union all
select 2, 3, 'a3' union all
-- 第一行 a1 第二行 a2 b2 第三行 a3 b3 第四行 a4 b4 c4
select 3, 1, 'a1' union all
select 3, 2, 'a2' union all
select 3, 2, 'b2' union all
select 3, 3, 'a3' union all
select 3, 3, 'b3' union all
select 3, 4, 'a4' union all
select 3, 4, 'b4' union all
select 3, 4, 'c4'
select a.select_id, v1=a.val, v2=b.val from # a, # b
where a.select_id=b.select_id and a.row_id<>b.row_id and a.val<b.val
--and a.select_id=1
/*
select_id v1 v2
----------- -------- --------
1 a1 a2
1 a1 b2
2 a1 a2
2 a1 b2
2 a3 b2
2 a1 a3
2 a2 a3
...
*/
--假设列名为L1 , L2 , ... L6
如我现在的选择
第一行 a1
第二行 a2 b2
现在需要计算 已选择的行中选择两行,每行选出一个元素,这样的组合数有多少
如:这里的组合是(a1 a2),(a1 b2)两组,即排列组合的[C(2,2)C(2,1)]
select m.L1 , n.L2 from tb m,
(
select L1 L2 from tb where n.L1 = 'a2'
union all
select L2 from tb where n.L2 = 'b2'
) n
where m.L1 = 'a1'
假如我现在的选择是
第一行 a1
第二行 a2 b2
第三行 a3
这里的组合便是C(3,2)C(2,1)-C(2,2)=5 5个组合是(a1 a2)(a1 a3)(a2 a3)(a1 b2)(b2 a3)
select m.L1 , n.L2 from tb m,
(
select L1 L2 from tb where n.L1 = 'a2'
union all
select L2 from tb where n.L2 = 'b2'
) n
where m.L1 = 'a1'
unoin all
select m.L1 , n.L2 from tb m,
(
select L1 L2 from tb where n.L1 = 'a2'
union all
select L2 from tb where n.L2 = 'b2'
) n
where m.L1 = 'a3'