我目前有以下查询
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)上重复。以下是单曲(查理,唐纳德,佛罗伦萨,乔治)。
我想要的是2个不同的查询,其中一个查询应该只返回单个记录而另一个查询应该只返回重复。 “我需要同时从两个查询中返回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
答案 0 :(得分:4)
如果不是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
答案 1 :(得分:0)
使用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