0

这是一个 SQL 函数 - 对复杂性感到抱歉;

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

在描述中 - 有一个代码表,其中包含在表 RawData 中为每一列使用的代码。第二个名为 Categories 的表跟踪所有这些列,Codes.CategoryName 是 Categories.Name 的 FK。基本上为 RawData 中的每个编码值创建一个查找表。

字段 RawData.FS 有 3 个值 NULL、1 和 2。RawData.ACR 有 3 个值对应于小于 1 英亩、1-10 英亩、> 10 英亩的描述。上面的查询给出了正确的结果

Description                          FS Total Units
House on less than one acre               57080
House on one to less than ten acres        4760
House on ten acres or more                  880

House on less than one acre           1   31496
House on one to less than ten acres   1    4312
House on ten acres or more            1     360

House on less than one acre           2  594404
House on one to less than ten acres   2   74688
House on ten acres or more            2    9104

这里的挑战是重做 SQL,而不是 3 组 3 行,它们是对应于 FS 值的列。换句话说,标题将是(对于第一行);

Description                        FS=NULL    FS=1      FS=2    
House on less than one acre         57080    31496    594404   

作为更多帮助 - 这是创建类别和代码结构的 SQL

CREATE TABLE Categories (
 [Name] NVARCHAR(50) PRIMARY KEY,
 [Description] NVARCHAR(200) 
)

CREATE TABLE Codes (
 [Name] NVARCHAR(50),
 [CategoryName] NVARCHAR(50) FOREIGN KEY REFERENCES Categories(Name),
 [Description] NVARCHAR(200) ) 

RawData 中的每个字段都经过编码(实际上数据字典位于http://www.census.gov/acs/www/Downloads/data_documentation/pums/DataDict/PUMS_Data_Dictionary_2009-2011.pdf)。这是那些经典的 SQL 谜题之一。

4

2 回答 2

1

听起来您想要执行以下操作,将值转换FS为列:

SELECT [Codes].[Description], 
  sum(case when RawData.FS is null then 1 else 0 end) FS_null,
  sum(case when RawData.FS = 1 then 1 else 0 end) FS_1,
  sum(case when RawData.FS = 2 then 1 else 0 end) FS_2
FROM RawData
INNER JOIN Codes
  ON RawData.ACR = Codes.Name
INNER JOIN Categories  
  ON Codes.CategoryName = Categories.Name
WHERE Codes.CategoryName = 'ACR'
GROUP BY [Codes].[Description]
于 2013-02-04T22:07:15.013 回答
0

未经测试,但似乎一个案例和一个子选择会起作用。

Select description, 
case when fs is null then total_units end as 'FS=Null',
CASE WHEN fs = 1 then total_units end as 'FS=1',
case when fs = 2 then total_units end as 'FS=2'
FROM (
  SELECT [Codes].[Description], 
  RawData.FS, COUNT(*)  As 'Total_units' 
  FROM RawData, Codes, Categories  
  WHERE RawData.ACR = Codes.Name
  AND   Codes.CategoryName = 'ACR'
  GROUP BY [Codes].[Description])
ORDER BY description
于 2013-02-04T22:11:52.647 回答