仅显示具有准确三项的用户的SQL结果

时间:2019-05-26 13:41:13

标签: sql sql-server database

SELECT * 
FROM PlanData 
WHERE GeneralEventCode = 'VM' 
  AND AirlineCode = 'LH' 
  AND DateStart > '2019-05-01' 
  AND UserHomeBaseAirportCode = 'FRA'

在此表中,我还具有字段UserId。如果一个UserId在该表中有3个条目,我只想得到结果。

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

您还需要在WHERE子句中增加1个条件,才能仅选择具有3个条目的UserId

SELECT * FROM PlanData 
where 
  GeneralEventCode='VM' 
  and AirlineCode='LH' 
  and DateStart>'2019-05-01' 
  and UserHomeBaseAirportCode='FRA'
  and UserId IN (
    SELECT UserId 
    FROM PlanData 
    GROUP BY UserId 
    HAVING Count(*) = 3
  )

答案 1 :(得分:0)

您可以使用窗口功能。以下假设您的意思是符合您条件的三行:

SELECT pd.*
FROM (SELECT pd.*,
             COUNT(*) OVER (PARTITION BY userid) as cnt
      FROM PlanData pd
      WHERE GeneralEventCode = 'VM' and
            AirlineCode='LH' and
            DateStart > '2019-05-01' and 
            UserHomeBaseAirportCode = 'FRA'
    ) pd
WHERE cnt = 3;

如果您指的是任何形式的三行,则:

SELECT pd.*
FROM (SELECT pd.*,
             COUNT(*) OVER (PARTITION BY userid) as cnt
      FROM PlanData pd
     ) pd
WHERE GeneralEventCode = 'VM' and
      AirlineCode='LH' and
      DateStart > '2019-05-01' and 
      UserHomeBaseAirportCode = 'FRA' and
      cnt = 3;