我有一个T-SQL select
语句,其中多列包含Case
语句,是或否(基于另一个表数据)
我有这两个表:
表1
Id | Location
----+------------
101 | Warsaw
102 | Belfast
104 | Singapore
106 | Texas
108 | Mumbai
109 | Virgina
表2 :
Id | AttrName | AttrId
----+------------+---------
101 | Datacenter | 99
101 | Cold | 88
102 | Datacenter | 99
102 | Cold | 88
106 | Datacenter | 99
108 | Cold | 88
查询输出应为:
Id | Location | Datacenter | Cold
----+-----------+------------+------
101 | Warsaw | YES | YES
102 | Belfast | YES | YES
104 | Singapore | NO | NO
106 | Texas | YES | NO
108 | Mumbai | NO | YES
109 | Virgina | NO | NO
请让我知道我们如何实现这一目标。
答案 0 :(得分:0)
FROM table1 as base
LEFT OUTER JOIN table2 as Datacenter on base.Id = Datacenter.Id and Datacenter.AttrName = 'Datacenter'
LEFT OUTER JOIN table2 as Cold on base.Id = Cold.Id and Cold.AttrName = 'Cold'
在SELECT中,您需要检查是否存在与table2的特定别名匹配的查找,以定义从AttrName派生的列:
CASE WHEN Datacenter.Id IS NOT NULL THEN 'YES' ELSE 'NO' END as Datacenter
答案 1 :(得分:0)
我会改用PIVOT。它可以执行得更好,但是我会检查每个执行计划以确保。在比较计划之前,只需确保将查询重定向到实际表(而不是这些表变量进行测试)即可。祝好运! :)
DECLARE @Table1 TABLE (
Id BIGINT NOT NULL PRIMARY KEY,
Location VARCHAR(100) NOT NULL,
UNIQUE CLUSTERED (Id)
);
INSERT INTO @Table1
(Id, Location)
VALUES
(101,'Warsaw'),
(102,'Belfast'),
(104,'Singapore'),
(106,'Texas'),
(108,'Mumbai'),
(109,'Virgina');
DECLARE @Table2 TABLE (
Id BIGINT NOT NULL,
AttrName VARCHAR(100) NOT NULL,
AttrId BIGINT NOT NULL,
UNIQUE CLUSTERED (Id,AttrId)
);
INSERT INTO @Table2
(Id, AttrName, AttrId)
VALUES
(101,'Datacenter',99),
(101,'Cold',88),
(102,'Datacenter',99),
(102,'Cold',88),
(106,'Datacenter',99),
(108,'Cold',88);
WITH CTE_Table2 AS (
SELECT
Id,
Datacenter,
Cold
FROM (
SELECT
t.Id,
t.AttrName,
'YES' AS Bool
FROM @Table2 AS t
) AS b
PIVOT (
MAX(Bool)
FOR AttrName IN ([Datacenter],[Cold])
) AS p
)
SELECT
t1.Id,
t1.Location,
ISNULL(t2.Datacenter,'NO') AS Datacenter,
ISNULL(t2.Cold,'NO') AS Cold
FROM @Table1 AS t1
LEFT JOIN CTE_Table2 AS t2
ON t1.Id = t2.Id;
答案 2 :(得分:0)
下面是要解决的其他选项,它使用EXISTS
,
-- delcare table variables
declare @t1 table (Id int, Location nvarchar(20))
declare @t2 table (Id int, AttrName nvarchar(20), AttrId int)
-- insert test data
insert into @t1
values (101, 'Warsaw'),
(102, 'Beflast'),
(104, 'Singapore'),
(106, 'Texas'),
(108, 'Mumbai'),
(109, 'Virginia')
insert into @t2
values (101, 'Datacentre', 99),
(101, 'Cold', 88),
(102, 'Datacentre', 99),
(102, 'Cold', 88),
(106, 'Datacentre', 99),
(108, 'Cold', 88)
-- query
select
t1.Id,
Location,
case when exists (select 1 from @t2 t2 where t2.AttrId = 99 and t1.id = t2.id) then 'yes' else 'no' end as Datacentre,
case when exists (select 1 from @t2 t2 where t2.AttrId = 88 and t1.id = t2.id) then 'yes' else 'no' end as Cold
from @t1 t1
结果
Id Location Datacentre Cold
101 Warsaw yes yes
102 Beflast yes yes
104 Singapore no no
106 Texas yes no
108 Mumbai no yes
109 Virginia no no