Problem with LIMIT & IN/ALL/ANY/SOME subquery

后端 未结 4 1664
予麋鹿
予麋鹿 2020-12-06 01:50

I have this query:

SELECT count(cp.CxID) as intSmokers 
FROM CustPrimarySmoking cp 
JOIN Customer c ON cp.CxID = c.CustomerID 
WHERE 
cp.CxID IN (SELECT CxID         


        
4条回答
  •  生来不讨喜
    2020-12-06 02:33

    This limitation is a pain if you want to get something like "top N rows for each group". But in your case I wouldn't use that feature even if it were possible. What you try to do is to count all rows except of one row each CxID. All you need is just to subtract the number of distinct CustomerIDs, which is count(DISTINCT cp.CxID). So your final query should be as simple as:

    SELECT count(cp.CxID) - count(DISTINCT cp.CxID) as intSmokers 
    FROM CustPrimarySmoking cp
    

提交回复
热议问题