我有以下查询..现在我必须检查相同的列是否有相同的数据..
任何人都可以帮我查询pls
SELECT
FirstName, MiddleName, LastName, Company, TaxExempt,
AddressTitle, AddressLine1, AddressLine2, City, [State], ZipCode, Country,
PhoneNumber, EmailID,
o.OrderNumber, o.PONumber
FROM
CustomerAddresses ca
JOIN Orders o
ON ca.CustomerID = o.CustomerID
WHERE
AddressTitle='Billing'
答案 0 :(得分:6)
一个常见的技巧是按所有内容进行分组并计算:
SELECT count(1) as [Count],
FirstName, MiddleName, LastName, Company, TaxExempt,
AddressTitle, AddressLine1, AddressLine2, City, [State], ZipCode, Country,
PhoneNumber, EmailID,
o.OrderNumber, o.PONumber
FROM
CustomerAddresses ca
JOIN Orders o
ON ca.CustomerID = o.CustomerID
WHERE
AddressTitle='Billing'
group by
FirstName, MiddleName, LastName, Company, TaxExempt,
AddressTitle, AddressLine1, AddressLine2, City, [State], ZipCode, Country,
PhoneNumber, EmailID,
o.OrderNumber, o.PONumber
您可以添加:
having count(1) > 1
如果你只关心副本并且不想看单打,那么在底部。
答案 1 :(得分:1)
使用Common Table Expressions查找对其进行分组的所有行产生的计数大于1。然后将该结果连接回CustomerAddress表以获取每个地址的ID。
WITH Billing_CTE
(SELECT FirstName, MiddleName, LastName, Company, TaxExempt, AddressTitle, AddressLine1, AddressLine2, City, [State], ZipCode, Country, PhoneNumber, EmailID, o.OrderNumber, o.PONumber, Count(1) AS [DupCount]
FROM CustomerAddresses ca
JOIN Orders o ON ca.CustomerID = o.CustomerID
WHERE AddressTitle='Billing'
GROUP BY FirstName, MiddleName, LastName, Company, TaxExempt, AddressTitle, AddressLine1, AddressLine2, City, [State], ZipCode, Country, PhoneNumber, EmailID, o.OrderNumber, o.PONumber HAVING Count(1) > 1)
SELECT ca.CustomerId,
o.OrderNumber,
o.PONumber
FROM Billing_CTE b
JOIN Oderers o ON b.OrderNumber = o.OrderNumber
AND b.PONumber = o.PONumber