gpt4 book ai didi

SQL 条件 GROUP BY : how to do it?

转载 作者:可可西里 更新时间:2023-11-01 07:21:37 25 4
gpt4 key购买 nike

假设我有以下 SQL 查询:

SELECT Meeting.id AS meetingId, Bill.id AS billId
FROM Meeting
LEFT JOIN Bill ON Meeting.FK_BillId = Bill.id

输出如下:

meetingId | billId
------------------
a | NULL
b | NULL
c | 1
d | 1
e | 1
f | 2
g | 2

我想要以下输出,按非 NULL 的 billId 分组:

meetingId | billId
------------------
a | NULL
b | NULL
c | 1
f | 2

我怎样才能做到这一点?顺便说一句,我不关心分组结果的模棱两可的 meetingId。

感谢您的帮助!

最佳答案

SQL Server :

SELECT  meetingId, billid
FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY billId ORDER BY meetingID) AS rn,
m.*
FROM mytable m
) q
WHERE rn = 1 OR billid IS NULL

ANSI :

SELECT  MIN(meetingId), billid
FROM mytable
WHERE billid IS NOT NULL
GROUP BY
billId
UNION ALL
SELECT meetingId, billId
FROM mytable
WHERE billid IS NULL

MySQL :

SELECT  meetingId, billid
FROM mytable
WHERE billid IS NOT NULL
GROUP BY
billId
UNION ALL
SELECT meetingId, billId
FROM mytable
WHERE billid IS NULL

这比 MIN 效率高一点点如果你真的不关心什么meetingID只要属于正确的组,就会返回。

关于SQL 条件 GROUP BY : how to do it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1410430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com