在SQL中更改聚合函数中的行/列

时间:2013-02-04 22:02:03

标签: sql sql-server database aggregation

这是一个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英亩的描述,> 1。 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难题之一。

2 个答案:

答案 0 :(得分:1)

听起来您想要执行以下操作,将<{1}}值分配到列中:

FS

答案 1 :(得分: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