列出超过一半的学生接受的城市

时间:2015-01-28 20:06:20

标签: sql sql-server

我有两张桌子:

tbl1:schoolID schoolname

tbl2 StudentID,schoolID,Stu_Name,地址,城市,州,状态

“状态”字段包含接受值A或拒绝

的R.

我需要列出纽约州的城市,其中超过一半的学生申请被接受。

1 个答案:

答案 0 :(得分:1)

示例表格

SELECT * INTO #tbl1 FROM
(
   SELECT 1 schoolID,'SchoolA' schoolname
   UNION ALL
   SELECT 1,'SchoolB'
)TAB 


SELECT * INTO #tbl2 FROM
(
   SELECT 1 StudentID,1 schoolID ,'A' Stu_Name,'XXX' address,'CITYA' [CITY],'NY' [STATE],'A' [STATUS]
   UNION ALL
   SELECT 2,1,'A','XXX','CITYA','NY','A'
   UNION ALL
   SELECT 3,1,'A','XXX','CITYA','NY','A'
   UNION ALL
   SELECT 4,1,'A','XXX','CITYA','NY','A'
   UNION ALL
   SELECT 14,1,'A','XXX','CITYA','NY','R'
   UNION ALL
   SELECT 5,1,'A','XXX','CITYA','NY','R'
   UNION ALL
   SELECT 6,1,'A','XXX','CITYA','NY','R'
   UNION ALL
   SELECT 7,1,'A','XXX','CITYB','NY','A'
   UNION ALL
   SELECT 8,1,'A','XXX','CITYB','NY','A'
   UNION ALL
   SELECT 9,1,'A','XXX','CITYC','NY','A'
   UNION ALL
   SELECT 10,1,'A','XXX','CITYC','NY','R'
)TAB

<强> QUERY

如果您需要查找超过一半学生申请被接受的城市,无论学校如何,您都可以按照以下查询。

DECLARE @CITY VARCHAR(30)='NY'

SELECT [CITY]
FROM
(
    SELECT DISTINCT [CITY]
    ,CASE WHEN 
    (
       -- Gets half of total count
       COUNT([STATUS]) OVER(PARTITION BY [CITY])/2) 
       >= 
       -- Checks if half of total count is greater than count of accepted for each cities
       COUNT(CASE WHEN [STATUS]='A' THEN 1 END) OVER(PARTITION BY [CITY]
    ) 
    THEN 'N' 
    ELSE 'Y' 
    END ACCEPTED
    FROM #tbl2
    WHERE [CITY] = @CITY
)TAB
WHERE ACCEPTED='Y'

如果您想通过学校过滤此条件,可以按照以下查询

DECLARE @SCHOOLID INT = 1
DECLARE @CITY VARCHAR(30)='NY'

SELECT [CITY]
FROM
(
    SELECT DISTINCT [CITY]
    ,CASE WHEN 
    (
       COUNT([STATUS]) OVER(PARTITION BY [CITY])/2) 
       >= 
       COUNT(CASE WHEN [STATUS]='A' THEN 1 END) OVER(PARTITION BY [CITY]
    ) 
    THEN 'N' 
    ELSE 'Y' 
    END ACCEPTED
    FROM #tbl1 T1
    JOIN #tbl2 T2 ON T1.schoolID=T2.schoolID AND T1.schoolID=@SCHOOLID
    WHERE [CITY] = @CITY 
)TAB
WHERE ACCEPTED='Y'