我有表" table1",其中包含以下行:
ColA ColB
-------------
p4 x1
p4 z
p4 z
p5 s
p5 t
p5 y1
p8 x1
p8 y1
p8 x1
p9 x1
p10 z1
p1 z1
p2 z1
p3 z1
现在我需要显示一个这样的表:(如预期的那样)
ColA ColB Result
----------------------
p4 x1 0
p8 x1 0
p9 x1 0
p5 y1 0
p8 y1 0
p1 z1 0
p10 z1 0
p2 z1 0
p3 z1 0
我正在撰写查询:
with cte
as
(
select colb,cola,dense_rank() over(partition by colb order by cola asc) tem
from table1
)
select s.cola, s.colb, 0 as result into tem_table
from table1 s
inner join cte c on c.colb = s.colb
where tem > 1
group by s.cola,s.colb
order by s.colb;
但我不想在上面的查询中使用内连接,因为它具有较低的性能。所以我在尝试查询:
with cte as
(
select colb,cola,dense_rank() over(partition by colb order by cola asc) tem
from table1
)
select cola,colb,0 as result into tem_table from cte
where tem > 1
group by cola,colb
order by colb;
这给出了一个输出:(这是不正确的)
ColA ColB Result
----------------------
p8 x1 0
p9 x1 0
p8 y1 0
p10 z1 0
p2 z1 0
p3 z1 0
如何在CTE中不使用内部联接的情况下获得预期的输出,因为它是自己加入的 更多时间执行。
答案 0 :(得分:1)
SELECT colA, colB, 0
FROM (
SELECT colA, colB, COUNT(*) OVER (PARTITION BY colB) cnt
FROM (
SELECT DISTINCT colA, colB
FROM mytable
) q
) q
WHERE cnt > 1