需要帮助使用TSQL创建查询

时间:2013-01-11 11:47:42

标签: sql-server database tsql

我有一个包含以下结构和数据的表:

ID_A | ID_B
 A      1
 A      2
 B      1
 B      2
 C      1
 C      3
 D      1
 D      2
 D      3

我需要找到给出A id的不同B组。在示例中,结果将是:

  1. 1,2
  2. 1,3
  3. 1,2,3
  4. 如果我能得到计数那就太棒了:

    1. 1,2 [2]
    2. 1,3 [1]
    3. 1,2,3 [1]
    4. 我希望这个问题是明确的。谢谢!

1 个答案:

答案 0 :(得分:3)

SQL Fiddle

MS SQL Server 2012架构设置

create table YourTable
(
  ID_A char(1),
  ID_B int
)

insert into YourTable values
( 'A',      1),
( 'A',      2),
( 'B',      1),
( 'B',      2),
( 'C',      1),
( 'C',      3),
( 'D',      1),
( 'D',      2),
( 'D',      3)

查询1

select T.ID_B,
       count(*) as C
from
  (
  select T1.ID_A,
         (
         select ','+cast(T2.ID_B as varchar(10))
         from YourTable as T2
         where T2.ID_A = T1.ID_A
         order by T2.ID_B
         for xml path(''), type
         ).value('substring(text()[1], 2)', 'varchar(max)') as ID_B
  from YourTable as T1
  group by T1.ID_A
  ) as T
group by T.ID_B

<强> Results

|  ID_B | C |
-------------
|   1,2 | 2 |
| 1,2,3 | 1 |
|   1,3 | 1 |