我当前有以下查询
SELECT table1.col1, table2.col2
FROM table1
INNER JOIN table2 ON table1.col1=table2.col6
WHERE col3 IN
(SELECT col1
FROM table3
WHERE col4 IN (
SELECT col4
FROM table4
WHERE col5 LIKE '%XYZ%'
)
) ORDER BY table1.col1
我得到的结果如下
COL1 | COL2
Bob LA
BOB NY
Charlie SF
Donald Phoenix
Edward Chicago
Edward DC
Florence Miami
George Sunnyvale
Helen Orlando
Helen Houston
如果观察结果,以下条目将在Col1上重复(Bob、Edward、Helen)。以下仅为单一唱片(查理、唐纳德、弗洛伦斯、乔治)。
我想要的是两个不同的查询,其中一个查询应该只返回单个记录,而另一个查询则应该只返回重复的记录。"我需要从两个查询中返回Col1和Col2"。我已经尝试过修改,但要么它给出了错误,要么它没有导致任何重用。
期望结果
Query1结果(仅单个记录)
COL1 | COL2
Charlie SF
Donald Phoenix
Florence Miami
George Sunnyvale
Query2结果(只返回重复记录)
COL1 | COL2
Bob LA
BOB NY
Edward Chicago
Edward DC
Helen Orlando
Helen Houston
如果不是Oracle,请熟悉GROUP BY xxx HAVING yyy = z
构造。
简单地将其添加到查询中是行不通的,因为您还想选择一个不按分组的列,但这里有一种简单的吃蛋糕和吃蛋糕的方法:
SELECT table1.col1, table2.col2
FROM table1
INNER JOIN table2 ON table1.col1=table2.col6
WHERE col3 IN
(SELECT col1
FROM table3
WHERE col4 IN (
SELECT col4
FROM table4
WHERE col5 LIKE '%XYZ%'
)
)
AND col1 IN (
SELECT table1.col1
FROM table1
INNER JOIN table2 ON table1.col1=table2.col6
WHERE col3 IN
(SELECT col1
FROM table3
WHERE col4 IN (
SELECT col4
FROM table4
WHERE col5 LIKE '%XYZ%'
)
)
GROUP BY table1.col1
HAVING COUNT(table1.col1) > 1
)
ORDER BY table1.col1
使用oracle,分析函数是您的朋友。如果你不介意在数据中增加一列,你可以这样做:
对于单一结果:
SELECT
table1.col1,
table2.col2,
count(*) over(partition by table1.col1) AS col1count
FROM table1
INNER JOIN table2 ON table1.col1=table2.col6
WHERE col3 IN
(SELECT col1
FROM table3
WHERE col4 IN (
SELECT col4
FROM table4
WHERE col5 LIKE '%XYZ%'
)
) ORDER BY table1.col1
AND col1count = 1
对于副本,只需将最后一行更改为
AND col1count > 1