如何更改此查询以便它仅基于表列中的是或否条目返回数据?

时间:2017-07-21 19:18:46

标签: sql sql-server lookup-tables

这是查询的核心     使用FloridaHousingDB

SELECT   [Codes].[Description],  COUNT(*) As 'Number Units' 
FROM     HousingInfo, Codes, Categories 
WHERE    HousingInfo.ACR = Codes.Name
AND    Codes.CategoryName = 'ACR'
AND    Categories.Name = Codes.CategoryName
GROUP BY [Codes].[Description]

目前以此格式返回

House on less than one acre 170745

House on one to less than ten acres 20940

House on ten acres or more  2586

我需要做的是弄清楚如何以相同的格式进行选择,除了它只返回FS值为Yes的单位数,其中YES位于描述栏下

Name CategoryName Description
1   REGION         Northeast
2   REGION         Midwest
3   REGION         South
4   REGION         West
9   REGION         Puerto Rico
1   TYPE           Housing Unit
2   TYPE           Institutional Group Quarters
1   TYPE           Noninstitutional Group Quarters
b   ACR            N/A
1   ACR            House on less than one acre
2   ACR            House on one to less than ten acres
3   ACR            House on ten acres or more
b   FS             N/A
1   FS             Yes
2   FS             No
NULL    NULL    NULL

2 个答案:

答案 0 :(得分:0)

如果我已经充分破译了你的问题,我认为你只需要修改你的WHERE条款,同时也包括'FS'代码,并附上'YES'的描述:

SELECT   [Codes].[Description],  COUNT(*) As 'Number Units' 
FROM     HousingInfo, Codes, Categories 
WHERE    HousingInfo.ACR = Codes.Name
AND    Categories.Name = Codes.CategoryName
AND    (
            Codes.CategoryName = 'ACR'
            OR
                (
                    Codes.CategoryName = 'FS'
                    AND 
                    Codes.Description = 'YES'
                )
        )
GROUP BY [Codes].[Description]

答案 1 :(得分:0)

同意斯坦。这是更现代的连接语法:

选择[代码]。[描述],COUNT(*)作为'数字单位' 来自HousingInfo          HousingInfo.ACT = Codes.Name上的内连接代码          Categories.Name = Codes.CategoryName上的内连接类别 在哪里(             Codes.CategoryName ='ACR'             要么                 (                     Codes.CategoryName ='FS'                     和                     Codes.Description ='是'                 )         ) GROUP BY [代码]。[描述]