我有一个查询,我想与自己进行比较 - 到目前为止这个查询是有效的(如果有一个更整洁/更好的方式来编写它我想知道!)但它产生一些“重复”值。
SELECT
a.GroupID,
a.MemberH,
a.ChartID as ChartIDA,
b.ChartID as ChartIDB
FROM
(Select DISTINCT
s.GroupID,
c.ChartID,
m.MemberH
From Charts c, ChartRetrieval cr, Sites s, Members m
Where
c.ChartID=cr.ChartID
and cr.ChartScanningStatusID <> 331
and s.SiteID=c.SiteID
and s.ProjectID not in (1,2,111)
and m.MemberID=c.MemberID) a
INNER JOIN
(Select DISTINCT
s.GroupID,
c.ChartID,
m.MemberH
From Charts c, ChartRetrieval cr, Sites s, Members m
Where
c.ChartID=cr.ChartID
and cr.ChartScanningStatusID <> 331
and s.SiteID=c.SiteID
and s.ProjectID not in (1,2,111)
and m.MemberID=c.MemberID) b ON a.GroupID=b.GroupID AND a.MemberHICN=b.MemberHICN
WHERE
a.GroupID=b.GroupID
and a.MemberH=b.MemberH
and a.ChartID <> b.ChartID
Order By a.GroupID
到目前为止,结果是正确的,但正如我所说,它给了我一些欺骗。
IE -
Group ID | MemberH | ChartIDA | ChartIDB
-----------------------------------------
471021 | 810392941 | 4810391 | 2193845
-----------------------------------------
471021 | 810392941 | 2193845 | 4810391
我知道这些行在技术上并不重复,但信息是相同的只是翻转(所以对我来说,他们是dupes大声笑)。
我有办法解决这个问题吗?
答案 0 :(得分:1)
这是半答案,因为它不包括重复的行。您可以自行加入CTE以获得较小的查询:
;WITH SomeQuery AS (
SELECT
a.GroupID,
a.MemberH,
a.ChartID as ChartIDA,
b.ChartID as ChartIDB
FROM
(Select DISTINCT
s.GroupID,
c.ChartID,
m.MemberH
From Charts c, ChartRetrieval cr, Sites s, Members m
Where
c.ChartID=cr.ChartID
and cr.ChartScanningStatusID <> 331
and s.SiteID=c.SiteID
and s.ProjectID not in (1,2,111)
and m.MemberID=c.MemberID)
)
SELECT A.*
FROM SomeQuery A
INNER JOIN SomeQuery B
ON A.GroupID = B.GroupID AND A.MemberHICN = B.MemberHICN
WHERE
A.GroupID = B.GroupID
and A.MemberH = B.MemberH
and A.ChartID <> B.ChartID
Order By A.GroupID
有关Common Table Expressions here的更多信息。
答案 1 :(得分:1)
一个简单的伎俩:
and a.ChartID <> b.ChartID
而不是
and a.ChartID < b.ChartID
这将只显示两行中的一行。