SQL Server 2000:带有条件的透视

时间:2016-03-15 16:11:07

标签: sql-server stored-procedures sql-server-2000

我四处搜寻但找不到相似的答案。

在SQL Server 2000中使用条件排除NULL和'NA'字符串的推荐最佳方法是什么?

我想从这里开始(仅选择order_id = 100和line_no = 1):

+----------+---------+-----+------+-----+------+----+
| order_id | line_no |  a  |  b   |  c  |  d   | e  |
+----------+---------+-----+------+-----+------+----+
|      100 |       1 | 123 | NULL | NA  | 456  | X1 |
|      101 |       1 | 789 | NA   | 123 | NULL | BB |
+----------+---------+-----+------+-----+------+----+

对此:

+----------+---------+------+--------+
| order_id | line_no | type | config |
+----------+---------+------+--------+
|      100 |       1 | a    | 123    |
|      100 |       1 | d    | 456    |
|      100 |       1 | e    | X1     |
+----------+---------+------+--------+

1 个答案:

答案 0 :(得分:1)

在SQL Server 2000中,可用的选项不多。您可以使用UNION ALL

SELECT 'a' AS type, a
FROM mytable
WHERE a IS NOT NULL AND a <> 'NA'

UNION ALL 

SELECT 'b' AS type, b
FROM mytable
WHERE b IS NOT NULL AND b <> 'NA'

UNION ALL 

SELECT 'c' AS type, c
FROM mytable
WHERE c IS NOT NULL AND c <> 'NA'

UNION ALL 

SELECT 'd' AS type, d
FROM mytable
WHERE d IS NOT NULL AND d <> 'NA'