基于列2和列3的排列在SQL Server中查询表
我有一张这样的桌子:基于列2和列3的排列在SQL Server中查询表,sql,sql-server,Sql,Sql Server,我有一张这样的桌子: col1 col2 col3 111 1 1 222 1 0 333 0 1 444 0 0 这里的col2=1意味着col1是商业性的,col3=1意味着col1也是零售性的。我如何得到下面这样的结果 ID Description 111 Commercial 111 Retail 222 Commercial 333 Reta
col1 col2 col3
111 1 1
222 1 0
333 0 1
444 0 0
这里的col2=1
意味着col1
是商业性的,col3=1
意味着col1
也是零售性的。我如何得到下面这样的结果
ID Description
111 Commercial
111 Retail
222 Commercial
333 Retail
您可以使用
联合所有
:
SELECT ID = col1, 'Commercial' FROM MyTable WHERE col2=1
UNION ALL
SELECT ID = col1, 'Retail' FROM MyTable WHERE col3=1
使用与上面几乎相同的方法,但只在一个结果集中使用
Select ID = col1, t.Description
from MyTable
cross apply (select Description = 'Commercial' where col2 = 1 union
select Description = 'Retail' where coll3 = 1)t
可以通过
UNPIVOT
完成,也可以:
DECLARE @t TABLE
(
col1 INT ,
col2 INT ,
col3 INT
)
INSERT INTO @t
VALUES ( 111, 1, 1 ),
( 222, 1, 0 ),
( 333, 0, 1 ),
( 444, 0, 0 )
SELECT col1 ,
CASE WHEN col = 'col2' THEN 'Commercial'
ELSE 'Retail'
END AS Description
FROM @t UNPIVOT( r FOR col IN ( [col2], [col3] ) ) u
WHERE r <> 0
DECLARE@t表
(
col1 INT,
col2 INT,
col3 INT
)
插入@t
值(111,1,1),
( 222, 1, 0 ),
( 333, 0, 1 ),
( 444, 0, 0 )
选择col1,
当col='col2'然后是'Commercial'时的情况
其他“零售”
以描述结尾
从@t UNPIVOT(r表示列IN([col2],[col3])u
其中r0
如果你想引用另一个答案,通常最好链接到它(每个答案下面都有一个共享链接,可以给你一个URL,我通常会使用“DasbLinkedLight的答案”这样的短语作为链接文本),而不是使用“上面”这样的“位置”语言,答案的位置可以根据投票和接受情况而改变。dasblinkenlight的答案也只有一个结果集。