我想做一个类似于SQL的语句,我无法理解它。
如果我的 TABLE_A 看起来像这样:
[dbo].[TABLE_A](
[EmpID] [INT],
[FName] [varchar](50) NULL,
[LName] [varchar](50) NULL
)
...我的 TABLE_B 如下所示:
[dbo].[TABLE_B](
[EmployeeActivity] [varchar](50) NULL,
[EmpID] [INT]
)
有人可以帮我写一个查询来做这样的事情:
FOR EACH DISTINCT [EmployeeActivity] RETURN
[TABLE_B].[EmployeeActivity],
[TABLE_A].[FName],
[TABLE_A].[LName],
[TABLE_A].[EmpID],
CASE
WHEN ([TABLE_B].[EmployeeActivity] IS NULL) THEN ('NO')
ELSE 'YES'
END
结果应该如下:
FireDrill12, Bill, Jones, 342,YES
FireDrill13, Bill, Jones, 342,NO
FireDrill14, Bill, Jones, 342,YES
FireDrill12, Smith, Sue, 253,NO
FireDrill13, Smith, Sue, 253,NO
FireDrill14, Smith, Sue, 253,YES
我无法理解这一点。
感谢您的帮助,
-Allen
答案 0 :(得分:1)
SELECT DISTINCT
[TABLE_A].[EmpID], [TABLE_A].[FName], [TABLE_A].[LName]
, CASE
WHEN [TABLE_B].[EmployeeActivity] IS NULL THEN 'No'
ELSE 'Yes'
END AS [EmployeeActivity]
FROM [TABLE_A]
LEFT JOIN [TABLE_B]
ON [TABLE_B].[EmpID] = [TABLE_A].[EmpID]
答案 1 :(得分:0)
SQL无论如何都是一种基于集合的语言,所以它已经为每个"做了事情,所以理论上你可以做一个CROSS JOIN来获得每个组合,用相关的查询来做你的检查,所以可能是这样的:
SELECT DISTINCT
b.EmployeeActivity,
a.FName,
a.LName,
a.EmpId,
CASE
WHEN EXISTS (SELECT 1 FROM [TABLE_B] c WHERE c.[EmployeeActivity] = b.EmployeeActivity AND c.EmpId = a.EmpId) THEN 'YES'
ELSE 'NO'
END
FROM Table_b AS b
CROSS JOIN Table_a AS a
ON a.EmpId = b.EmpId
答案 2 :(得分:0)
使用inner
加入的另一个版本,但使用left
加入的更正确的版本如@Blam
SELECT
A.*,
CASE
WHEN B.EmployeeActivity IS NULL THEN 'No'
ELSE 'Yes'
END
FROM
[dbo].[TABLE_A] A
INNER JOIN [dbo].[TABLE_B] B ON (A.EmpID = B.EmpID)
UNION
SELECT
A.*,
'No'
FROM
[dbo].[TABLE_A] A
WHERE
A.EmpID NOT IN (SELECT B.EmpID FROM [dbo].[TABLE_B] B)