简体   繁体   中英

How to find records ONLY having multiple rows in SQL Server 2014?

Customers have accounts with us for their vehicles. Some accounts have multiple vehicles.

I would like to create a report of accounts ONLY with multiple vehicles (ie Multiple AccountIDs and Licence Plate numbers.)

Table Account A
Table Plate 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

You could use having directly

    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

You got it almost .. need to use group by and having condition like

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

Use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM