我意识到这个问题的标题可能含糊不清,但我不确定如何用它来表达。我有下表:
i_id option p_id
---- ------ ----
1 A 4
1 B 8
1 C 6
2 B 3
2 C 5
3 A 7
3 B 3
4 E 11
如何根据每个唯一option
的{{1}}列的值选择行:如果i_id
存在,请选择该行,否则选择{{1}行使用'C'
的其他内容,以便结果集为:
'B'
答案 0 :(得分:2)
select i_id, option, p_id
from (
select
i_id,
option,
p_id,
row_number() over (partition by i_id order by case option when 'C' then 0 when 'B' then 1 when 'A' then 2 end) takeme
from thetable
where option in ('A', 'B', 'C')
) foo
where takeme = 1
答案 1 :(得分:2)
这将为您提供按C,B,A排序的值,同时删除任何没有这些值之一的i_id记录。
WITH ranked AS
(
SELECT i_id, [option], p_id
, ROW_NUMBER() OVER (PARTITION BY i_id ORDER BY CASE [option]
WHEN 'C' THEN 1
WHEN 'B' THEN 2
WHEN 'A' THEN 3
ELSE 4
END) AS rowNumber
FROM yourTable
WHERE [option] IN ('A', 'B', 'C')
)
SELECT r.i_id, r.[option], r.p_id
FROM ranked AS r
WHERE r.rowNumber = 1
答案 2 :(得分:1)
create table t2 (
id int,
options varchar(1),
pid int
)
insert into t2 values(1, 'A', 4)
insert into t2 values(1, 'B', 8)
insert into t2 values(1, 'C', 6)
insert into t2 values(1, 'E', 7)
select t2.* from t2,
(select id, MAX(options) as op from t2
where options <> 'E'
group by id) t
where t2.id = t.id and t2.options = t.op
答案 3 :(得分:1)
好吧,如果您可以为每个字母指定一个数字“得分”,我建议您可以更轻松地解决这个问题,这样“更好”的字母会有更高的分数。然后,您可以使用MAX为每个组查找选项具有最高“得分”的行。因为'A'&lt; 'B'&lt; 'C',我们可以在这里作弊并使用选项作为分数,因此:
SELECT t1.i_id, t1.option, t1.p_id
FROM thetable t1
INNER JOIN (SELECT t2.i_id, MAX(option)
FROM thetable t2
GROUP BY t2.i_id) AS maximums
ON t1.i_id = maximums.i_id
WHERE option != 'D'
这假设{i_id, option}
是表的自然键(即,没有两行对这两列具有相同的值组合;或者,您对该对具有唯一性约束列。)