MSSQL:在另一个表中选择出现次数超过2的行

时间:2011-10-05 10:47:05

标签: sql sql-server

基本上我需要获得一份在StaffOnGrade中出现超过2次的CampaignTitles列表,并列出等级等级高于2的CampaignTitle,StaffNo

WorksOn表:

CampaignTitle      | StaffNo
-------------------|--------
ADVENTURE WORLD    | 11
AIR CANADA         | 11
CARNIVAL CRUISES   | 3
CARNIVAL CRUISES   | 8
CARNIVAL CRUISES   | 9
FLIGHT CENTRE      | 7
FLIGHT CENTRE      | 10
HARVEYWORLD TRAVEL | 4
LAST MINUTE        | 4
PRINCESS CRUISES   | 3
PRINCESS CRUISES   | 5
PRINCESS CRUISES   | 6
PRINCESS CRUISES   | 7
PRINCESS CRUISES   | 11
TRAVELSCENE        | 10
VALUETOURS AUST    | 3
VIRGIN AUSTRALIA   | 10

StaffOnGrade表:

Grade | StaffNo
------|--------
1     | 2
2     | 11
3     | 3
3     | 6
3     | 7
4     | 4
4     | 8
4     | 10
5     | 5
5     | 9

以下两个查询实现了各个部分,但我需要将其作为一组查询结果返回。

SELECT campaigntitle, COUNT (CAMPAIGNTITLE) As [count]
FROM WORKSON
GROUP BY CAMPAIGNTITLE
HAVING COUNT(CAMPAIGNTITLE) >2

SELECT STAFFNO, GRADE
FROM STAFFONGRADE
WHERE GRADE > 2

希望这是有道理的!

1 个答案:

答案 0 :(得分:6)

SELECT campaigntitle, StaffNo, COUNT (CAMPAIGNTITLE) As [count]
  FROM WORKSON
 WHERE StaffNo IN
       (SELECT STAFFNO
          FROM STAFFONGRADE
         WHERE GRADE > 2)
 GROUP BY CAMPAIGNTITLE
HAVING COUNT(CAMPAIGNTITLE) >2