尝试执行以下命令时遇到了麻烦
我有一张表格,上面有病人的出入记录
My_table
ID NAME DATE TYPE PERFORMANCE_SCORE
103 John 08/12/18 EX 8
103 John 08/04/18 EN 5
105 Dave 06/22/18 EX 12
105 Dave 06/14/18 EN 16
108 Ben 02/07/19 EX 15
108 Ben 02/01/19 EN 19
其中EN =进入记录,EX =离开记录。我需要获取进入和退出记录,其中“退出记录(EX)”和“进入记录(EN)”之间的“ Performance_Score”差异为负。我希望最终结果会像
必填结果:
ID NAME DATE TYPE PERFORMANCE_SCORE
105 Dave 06/22/18 EX 12
105 Dave 06/14/18 EN 16
108 Ben 02/07/19 EX 15
108 Ben 02/01/19 EN 19
我试图像下面这样用Union来实现
select * from
(
SELECT
a.ID,
a.NAME,
a.DATE,
a.TYPE,
a.PERFORMANCE_SCORE
FROM My_table a
WHERE
a.TYPE = 'EX'
UNION ALL
SELECT
b.ID,
b.NAME,
b.DATE,
b.TYPE,
b.PERFORMANCE_SCORE
FROM My_table b
WHERE
b.TYPE = 'EN'
)
where a.ID = b.ID and a.NAME = b.NAME and b.PERFORMANCE_SCORE - a.PERFORMANCE_SCORE < 0 --> I know this condition can't be used outside the UNION block, but how can I implement this condition to get the result I need?
当我尝试像这样使用INNER JOIN
SELECT * FROM
(
SELECT
ID,
NAME,
DATE,
TYPE,
PERFORMANCE_SCORE
FROM My_table
WHERE
TYPE = 'EX'
)
a
INNER JOIN
(
SELECT
ID,
NAME,
DATE,
TYPE,
PERFORMANCE_SCORE
FROM My_table
WHERE
TYPE = 'EN'
)
b
ON
a.ID = b.ID AND a.NAME = b.NAME and b.PERFORMANCE_SCORE - a.PERFORMANCE_SCORE < 0
我得到了我需要的记录,但是它们都像下面一样排成一排
ID NAME DATE TYPE PERFORMANCE_SCORE ID NAME DATE TYPE PERFORMANCE_SCORE
105 Dave 06/22/18 EX 12 105 Dave 06/14/18 EN 16
108 Ben 02/07/19 EX 15 108 Ben 02/01/19 EN 19
我想念什么?
答案 0 :(得分:0)
具有EXISTS:
select t.* from my_table t
where exists (
select 1 from my_table
where
name = t.name
and
type = case when t.type = 'EX' then 'EN' else 'EX' end
and
(performance_score - t.performance_score) * (case when t.type = 'EX' then 1 else -1 end) > 0
)
答案 1 :(得分:0)
我在考虑窗口功能:
select t.*
from (select t.*,
sum(case when t.type = 'EX' then t.performance_score
when t.type = 'EN' then -t.performance_score
end) as diff_performance
from my_table t
where t.type in ('EX', 'EN')
) t
where diff_performance < 0;