[英]SQL Server 2014 : how to get records that have rows of different values of only particular column
[英]How to find records ONLY having multiple rows in SQL Server 2014?
客戶在我們的車輛上有我們的帳戶。 有些帳戶有多輛車。
我只想創建一個具有多個車輛的帳戶報告(即多個帳戶ID和車牌號)。
表帳戶A
餐盤P
A.AccountId = P.AccountId
SELECT A.AccountNumber
,A.AccountId
,P.LicPlateNo
FROM Account A
INNER JOIN Plate P ON A.AccountId = P.AccountId
WHERE A.RegDate > '2017-01-01'
AND (Select Count(P.LicPlateNo) GROUP BY A.AccountNumber) > 1
-- HAVING Count(P.LicPlateNo) > 1 ????
ORDER BY A.AccountNumber
您可以直接使用
SELECT A.AccountNumber
,A.AccountId
,P.LicPlateNo
FROM Account A
INNER JOIN Plate P ON A.AccountId = P.AccountId
WHERE A.RegDate > '2017-01-01'
GROUP BY A.AccountNumber
HAVING Count(P.LicPlateNo) > 1
ORDER BY A.AccountNumber
您幾乎了解了..需要使用group by
並having
條件
SELECT A.AccountNumber
,A.AccountId
,P.LicPlateNo
FROM Account A
INNER JOIN (
SELECT LicPlateNo, AccountId
FROM Plate
GROUP BY AccountId
HAVING Count(LicPlateNo) > 1 ) P
ON A.AccountId = P.AccountId
WHERE A.RegDate > '2017-01-01'
ORDER BY A.AccountNumber
使用count() over()
SELECT AccountNumber
,AccountId
,LicPlateNo
FROM (
SELECT A.AccountNumber
,A.AccountId
,P.LicPlateNo
,cnt = count(P.LicPlateNo) over(partition by P.AccountId)
FROM Account A
INNER JOIN Plate P ON A.AccountId = P.AccountId
WHERE A.RegDate > '2017-01-01'
) t
WHERE cnt > 1
ORDER BY AccountNumber
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.