我有一个类似于以下内容的select语句:
select *
from A
inner join B on A.id_x = B.id_x
inner join C on B.id_y = C.id_y
inner join D on C.id_z = D.id_z
where
A.date > '2014-01-01'
and A.id_y = 154
and D.id_t = 2
我想要的是做and count(A.id_x) > 1
这样的事情,它只返回原始选择中A.id_x
重复的部分。
这可能吗?
编辑:
我只是尝试使用临时表来解决它,使用我从T-SQL Insert into table without having to specify every column
获得的代码Select * Into
#tmpBigTable
From [YourBigTable]
但是我收到了一条错误消息,因为我的表格具有相同的列名,例如A.id_x
和B.id_x
。
"每个表中的列名必须是唯一的。"
是否有某种方法可以强制解决问题,或声明任意命名扩展名?
答案 0 :(得分:2)
select *
from A
inner join B on A.id_x = B.id_x
inner join C on B.id_y = C.id_y
inner join D on C.id_z = D.id_z
where
A.date > '2014-01-01'
and A.id_y = 154
and D.id_t = 2
AND A.id_x IN
(
SELECT A.id_x FROM A
GROUP BY A.id_x
HAVING count(A.id_x)>1);
答案 1 :(得分:1)
您可以使用窗口函数执行此操作:
select *
from (select *, count(*) over (partition by A.id_x) as cnt
from A inner join
B
on A.id_x = B.id_x inner join
C
on B.id_y = C.id_y inner join
D
on C.id_z = D.id_z
where A.date > '2014-01-01' and A.id_y = 154 and D.id_t = 2
) abcd
where cnt > 1;