通过带有后续列名

时间:2016-03-21 08:49:01

标签: sql sql-server

我有一个包含这样的列名的表;

+--------------------------------------------------------------------+-----------+
|                              BankTable                             |           |
+--------------------------------------------------------------------+-----------+
| Id | BANK1     | BANK2     | BRANCH1     | BRANCH2     | IBAN1     | IBAN2     |
+----+-----------+-----------+-------------+-------------+-----------+-----------+
| 1  | BANK1_ID1 | BANK2_ID1 | BRANCH1_ID1 | BRANCH2_ID1 | IBAN1_ID1 | IBAN2_ID1 |
+----+-----------+-----------+-------------+-------------+-----------+-----------+
| 2  | BANK1_ID2 | BANK2_ID2 | BRANCH1_ID2 | BRANCH1_ID2 | IBAN1_ID2 | IBAN2_ID2 |
+----+-----------+-----------+-------------+-------------+-----------+-----------+

我如何编写一个返回结果的查询;

 +------------------------------------------+
|                   BANK                   |
+------------------------------------------+
| ID | BANK      | BRANCH      | IBAN      |
+----+-----------+-------------+-----------+
| 1  | BANK1_ID1 | BRANCH1_ID1 | IBAN1_ID1 |
+----+-----------+-------------+-----------+
| 2  | BANK2_ID2 | BRANCH1_ID2 | IBAN2_ID2 |
+----+-----------+-------------+-----------+

P.s:我正在按Id列编写选择查询。 BTW查询结果每次都包含一行。

任何帮助表示感谢。

我不知道这是不是很好的方法,但我根据@Giorgos Betsos的答案解决了这个问题。以下是我如何解决这个问题。

SELECT BANK, BRANCH, IBAN
FROM (
    SELECT BANK1, BANK2, BRANCH1, BRANCH2, IBAN1, IBAN2
    FROM BankTable
    WHERE ID = your_id_here
) AS src
UNPIVOT (
    BANK FOR Col IN(BANK1, BANK2)
) AS unpvt1
UNPIVOT (
    BRANCH FOR Col1 IN(BRANCH1, BRANCH2)
) AS unpvt2
UNPIVOT (
    IBAN FOR Col2 IN(IBAN1, IBAN2)
) AS unpvt3
WHERE RIGHT(Col, 1) = RIGHT(Col1, 1)
    AND RIGHT(Col, 1) = RIGHT(Col2, 1)

2 个答案:

答案 0 :(得分:2)

您可以使用UNPIVOT

SELECT Bank
FROM (
  SELECT Id, BANK1, BANK2, BANK3, BANK4, BANK5
  FROM BankTable
  WHERE id = 1) AS src
UNPIVOT (
  Bank FOR Col IN([BANK1], [BANK2], [BANK3], [BANK4], [BANK5])) AS unpvt

Demo here

答案 1 :(得分:0)

如果列数更多,则可以使用动态SQL查询,如下所示:

<强>查询

declare @sql as varchar(max);

select @sql =stuff(
                (select 'union all select [' + column_name + '] as Bank 
                           from BankTable where Id = 1 ' 
                from information_schema.columns 
                where table_name = 'BankTable'
                and column_name like 'BANK[0-9]%'
                for xml path('')), 1, 9, '');

execute(@sql);

<强>结果

+-----------+
| Bank      |
+-----------+
| BANK1_ID1 |
| BANK2_ID1 |
| BANK3_ID1 |
| BANK4_ID1 |
| BANK5_ID1 |
+-----------+