我有一张桌子,下面有两种情况:
方案A:在职员工具有DateJoin
数据的一行
---- ---- ----
Name Column Value
---- ---- ----
Emp A DateJoin 20190701
方案B:辞职的员工的DateJoin
数据为空,插入了新的行调用ResignDate
---- ---- ----
Name Column Value
---- ---- ----
Emp A DateJoin NULL
Emp A ResignDate 20190702
对于第一种情况,很简单,我只需要获取行的值即可。但是对于第二种情况,DateJoin
将为空,因此我必须获取ResignDate
作为值。
我正在尝试通过以下查询(而不是有效的查询)实现这一目标:
SELECT e.Name,
-- Not working due to syntax error in CASE
CASE WHEN LEN(SELECT Value FROM ed WHERE Column = 'DateJoin') > 0
THEN SELECT Value FROM ed WHERE Column = 'DateJoin'
ELSE SELECT Value FROM ed WHERE Column = 'ResignDate'
END AS EmpDate
FROM employee e
INNER JOIN employee_date ed ON e.Name = ed.Name
如何使用CASE实现以上目标?还是有更好的主意来实现它?
答案 0 :(得分:0)
取决于数据的复杂性-我在下面提出了可以用作起点的
DROP TABLE IF EXISTS #t
SELECT 'emp A' AS [name] , 'datejoin' AS col , CAST('20190701' AS DATE) AS value
INTO #t
INSERT INTO #t
SELECT
'emp B',
'datejoin',
NULL
INSERT INTO #t
SELECT
'emp B',
'Resign',
'20190703'
SELECT name , MAX(value) AS date
FROM #t GROUP BY name
;WITH temp AS (
SELECT * , ROW_NUMBER() OVER ( PARTITION BY name ORDER BY value DESC ) AS rn FROM #t
)
SELECT temp.name , temp.col , temp.value
FROM temp
WHERE rn = 1