说我有一个像下面的表drafts
,其中sent_for_review
是布尔值:
rowid | title | author | sent_for_review
-------|--------|----------|-----------------
1 | Draft1 | John Doe | 0
2 | Draft2 | John Doe | 0
3 | Draft3 | John Doe | 1
4 | Draft4 | John Doe | 1
我想选择所有已发送以供审核的草稿。如果没有,则我要选择所有尚未发送以供审核的草稿。
我尝试了以下方法,尝试按sent_for_review
分组,然后仅选择最高的一个:
FROM drafts SELECT title WHERE author='John Doe'
GROUP BY sent_for_review HAVING MAX(sent_for_review)
但是,只有在Draft3和Draft4存在时,它才返回Draft3(应该返回两者)...,而在只有Draft1和Draft2存在时,它不返回任何东西(应该都返回)。
如何使其返回所有最大值?
答案 0 :(得分:2)
您可以使用窗口功能:
WITH cte AS (
SELECT *, DENSE_RANK() OVER(PARTITION BY author ORDER BY sent_for_review DESC) dr
FROM drafts
)
SELECT *
FROM cte
WHERE dr = 1
AND author='John Doe';
答案 1 :(得分:1)
与此:
select * from drafts
where
author='John Doe' and
sent_for_review = (select max(sent_for_review) from drafts where author='John Doe')
此查询:
select max(sent_for_review) from drafts where author='John Doe'
将返回:
1
(如果有草稿已送交审核,并且
0
(如果没有)
答案 2 :(得分:0)
我相信这是获得与卢卡兹的答案相同的功能的另一种方法(该功能比公认的答案更正确),但查询更简单。
create table drafts (title,author,sent_for_review);
insert into drafts values
('Draft1','Other Author',0),
('Draft2','Other Author',2),
('Draft1','John Doe',0),
('Draft2','John Doe',0),
('Draft3','John Doe',1),
('Draft4','John Doe',1);
select rowid,* from drafts a
where sent_for_review = (select max(sent_for_review)
from drafts
where author = a.author
group by author)
--and author='John Doe' --uncomment as needed
;