[英]Using DISTINCT inner join SQL
我有兩張桌子 T1 和 T2 我的桌子看起來像這樣
T1 [ID, AppKey, CommenterKey, Comment, NoteTime]
T2 [ID, UserKey, Firstname, Lastname]
T2 上的 UserKey 與 CommenterKey 相關
我想加入這兩個表,同時根據每個唯一的 AppKey 過濾評論列上的重復評論
任何關於如何使這項工作的想法將不勝感激。
這是示例數據:
這里的想法是過濾與某個 appkey 有關的重復評論,如果您查看 Appkey 列中的第 11-15 行它是相同的 appkey 如果您查看第 11-15 行它是相同的評論我想過濾這些評論out 所以查詢不會返回這些重復的行。
下面是我使用的查詢
SELECT Notes.Appkey,
Notes.CommenterKey,
Notes.Comment,
Notes.NoteTime,
Users.Firstname,
Users.Lastname
FROM tblNotes AS Notes
inner join
tblUsers AS Users ON Commenterkey = UserKey
您的示例數據很難閱讀。 但是,您可以使用row_number()
或聚合。 我認為這可以滿足您的要求:
select un.*
from (select n.Appkey, n.CommenterKey, n.Comment, n.NoteTime,
u.Firstname, u.Lastname,
row_number() over (partition by u.UserKey, n.Comment order by u.UserKey) as seqnum
from tblNotes n inner join
tblUsers u
on n.Commenterkey = u.UserKey
) un
where seqnum = 1;
根據示例數據,這樣的事情應該可以工作。
select n.NoteKey,
n.AppKey,
n.CommenterKey,
n.Comment,
u.Firstname,
u.Lastname
from Notes n
cross apply (
select AppKey,
CommenterKey,
Comment,
max(NoteTime) as NoteTime
from Notes n2
where n.AppKey = n2.AppKey
and n.CommenterKey = n2.CommenterKey
and n.Comment = n2.Comment
group by
n2.AppKey,
n2.CommenterKey,
n2.Comment
) ni
join Users u ON u.UserKey = n.CommenterKey
where ni.NoteTime = n.NoteTime
您最大的問題可能是性能。 您可能需要考慮添加重復標志並通過觸發器或計划作業進行檢查。
您還可以使用 CTE 表。 下面的鏈接是關於 CTE 表和如何使用它的介紹
https://www.essentialsql.com/introduction-common-table-expressions-ctes/
我認為這可以滿足您的要求,
with cte as
(
select notes.Appkey as appKey, notes.CommenterKey as CommenterKey, notes.Comment as Comment, notes.NoteTime as NoteTime,
users.Firstname as Firstname, users.Lastname as Lastname,
row_number() over (partition by users.UserKey, notes.Comment order by users.UserKey) as sequenceNo
from tblNotes as notes inner join
tblUsers as users
on notes.Commenterkey = users.UserKey
)
select * from cte where sequenceNo = 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.