Oracle11g的
我想知道玩家是否玩过游击手。但是,一个球员 甚至可能不在我的桌子上,但我还是想为那个玩家返回一排。在这种情况下,玩家#3不在桌子中,但我还是要返回一行。
选择标准
如果玩家至少有一个SHORTSTOP记录,那么只用YES返回1行。
如果玩家至少有一条记录而且没有一条是SHORTSTOP,那么只返回一行NO。
如果玩家没有记录,则只返回一行NO。
查询
with baseball_players as
(select 1 as player_id, 'SHORTSTOP' as position from dual union all
select 1 as player_id, 'FIRSTBASE' as position from dual union all
select 2 as player_id, 'FIRSTBASE' as position from dual)
select player_id, case position
when 'SHORTSTOP' then 'YES'
else 'NO'
end has_played
from baseball_players
where player_id in (1,2,3)
问题:如何编写查询以获得所需结果?
所需输出
PLAYER_ID HAS_PLAYED
----------------------
1 YES
2 NO
3 NO
答案 0 :(得分:1)
不是使用where子句,而是创建一个临时表,在你创建的表中插入值和左连接。
对IF NULL使用case语句,然后使用NO,否则为YES。
答案 1 :(得分:1)
这个怎么样:
WITH playerList AS
(
SELECT
1 player_id
FROM
dual
UNION
SELECT
2
FROM
dual
UNION
SELECT
3
FROM
dual
)
, baseball_players as
(
select 1 as player_id, 'SHORTSTOP' as position from dual union all
select 1 as player_id, 'FIRSTBASE' as position from dual union all
select 2 as player_id, 'FIRSTBASE' as position from dual
)
SELECT
pl.player_id
, MAX(CASE WHEN bp.position = 'SHORTSTOP' THEN 'YES' ELSE 'NO' END)
FROM
playerList pl
LEFT JOIN
baseball_players bp
ON
bp.player_id = pl.player_id
GROUP BY
pl.player_id