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

查询组合问题
有表 ID VALUE  
  1 A
  2 B
  3 C
  4 D
  .
  .
  .
要从value选择3个来组合 例如 ID VALUE  
  1 ABC
  2 ABD
  3 ACD
  4 BCD
只需查到其中一种组合,不需要重复的,如(ABC跟ACB归为一行ABC或ACB)请问如何查询

------解决方案--------------------
SQL code

--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
create table [test]([ID] int,[VALUE] varchar(1))
insert [test]
select 1,'A' union all
select 2,'B' union all
select 3,'C' union all
select 4,'D'

select px=ROW_NUMBER()over(order by (select 1)),
 a.[VALUE]+b.VALUE+c.VALUE as VALUE from test a
cross join test b
cross join test c
where a.VALUE<>b.VALUE and a.VALUE<>c.VALUE and b.VALUE<>c.VALUE
/*
px    VALUE
------------
1    BAC
2    BAD
3    CAB
4    CAD
5    DAB
6    DAC
7    ABC
8    ABD
9    CBA
10    CBD
11    DBA
12    DBC
13    ACB
14    ACD
15    BCA
16    BCD
17    DCA
18    DCB
19    ADB
20    ADC
21    BDA
22    BDC
23    CDA
24    CDB
*/