我有两个sql查询(来自1个表)我需要加入但是当我尝试加入它时我总是收到错误。
第一张表:这是完整的表格。
Select Server, Network, ReservationIP, ReservationMAC, ReservationName
from ScopeReservations
结果(截断。这是一张非常表格)
> Server Network ReservationIP ReservationMAC ReservationName
> Server1 10.3.64.32 10.3.64.36 000d5d08e83c pr-bnea06-a01-a
> Server2 10.3.64.32 10.3.64.37 000d5d08278c pr-bnea06-a02-a
第二张表:所有在ReservationMAC中具有重复值的人
Select ReservationMAC, COUNT(*) from DHCP_ScopeReservations
group by ReservationMAC
having count(*) > 1
order by ReservationMAC
结果:
ReservationMAC (No column name)
0000850a3477 2
0000854b8328 2
85731867 2
我需要的结果就是这个。
Server Network ReservationIP ReservationMAC ReservationName
Server1 10.233.192.0 10.233.192.5 0000850a3477 pq2217a.
Server2 10.233.196.0 10.233.197.129 0000850a3477 pq2217.
Server1 10.80.16.0 10.80.17.13 0000854b8328 PQ090.
Server2 10.80.70.32 10.80.70.47 0000854b8328 Canon4B8328.
此外,结果不应包含具有相同reservationIP和reservationMAC的结果。 不包括在结果中:
Server Network ReservationIP ReservationMAC ReservationName
Server1 10.34.57.0 10.34.57.10 011 vh101r
Server2 10.34.57.1 10.34.57.10 011 vh102r
Server1 10.206.0.0 10.206.3.22 0000681569af ac-gpo069
Server2 10.206.0.0 10.206.3.22 0000681569af ac-gpo069
结果应该是所有那些在ReservationMac列中有重复条目的人。结果必须包含表的所有列。
我试图做的事情:
Select a.Server, a.Network, a.ReservationIP, a.ReservationMAC,
a.ReservationName
from DHCP_ScopeReservations a
INNER JOIN
(
Select ReservationMAC, COUNT(*)
from DHCP_ScopeReservations
group by ReservationMAC
having count(*) > 1
) dt ON a.ReservationMAC=dt.ReservationMAC
错误是
Msg 8155,Level 16,State 2,Line 6 没有为'dt'的第2列指定列名。
答案 0 :(得分:1)
您需要声明COUNT(*)
的别名:
Select a.Server, a.Network, a.ReservationIP,
a.ReservationMAC, a.ReservationName, dt.cnt
from DHCP_ScopeReservations a
INNER JOIN (Select ReservationMAC, COUNT(*) AS cnt
from DHCP_ScopeReservations
group by ReservationMAC
having count(*) > 1) dt
ON a.ReservationMAC=dt.ReservationMAC
使用cnt
别名,您现在可以访问外部查询的SELECT
子句中的重复项数。
答案 1 :(得分:1)
使用JOIN
,您可以获得所需的结果,如下所示:
SELECT Server, Network, ReservationIP, s.ReservationMAC, ReservationName
FROM ScopeReservations s
JOIN (
SELECT ReservationMAC
FROM DHCP_ScopeReservations
GROUP BY ReservationMAC
HAVING COUNT(ReservationMAC) > 1
) dupe
ON s.ReservationMAC = dupe.ReservationMAC