2011-10-12 55 views
2

的样本数据:如何使用PIVOT子句在空白值

Data table1: 
prodid type location(there are more columns, just ignoring them for this example) 
p001  t1  l1 
p002  t1  l2 
p003  t3  l1 
p004  t2  
p005  t1  l1 

Need a summary like 
type Blank [l1] [l2] 
t1  0   2   1 
t2  1   0   0 
t3  0   1   0 

问题现在面临是在位置字段中的空白值。我不知道如何表示数据透视查询中的空白位置值。

Pivot query: 
1: select type, [] as Blank, [l1], [l2], Blank + [l1] + [l2] as Total from 
2: (select type, location from table1) 
3: pivot 
4: (count(location) for location in ([],[l1],[l2]) t2 

Error on line 1 & 4 
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Add a name or single space as the alias name. 

回答

2

如何只换出空/空位置为空值。因此,改变

select type, location from table1 

select type, CASE WHEN location is null THEN 'ZZ' ELSE location END as location from table1 

则列将是ZZ或任何虚拟价值选择

+0

我把CASE,因为我不知道你的位置是空字符串还是真正为空。如果它们为空,你可以使用isnull(location,'zz'),我认为这应该更有效一些。虽然如果你没有大量的数据,你不会注意到。 – PeteT

1

你可以只放弃PIVOT和使用

SELECT type, 
     COUNT(CASE 
       WHEN location = '' THEN 1 
      END) AS Blank, 
     COUNT(CASE 
       WHEN location = 'l1' THEN 1 
      END) AS l1, 
     COUNT(CASE 
       WHEN location = 'l2' THEN 1 
      END) AS l2, 
     COUNT(*) AS Total 
FROM table1 
WHERE location in ('','l1','l2') 
GROUP BY type 
+1

感谢您的快速反应马丁。 Acutal表具有更多位置值,并且可以更改。当我知道如何处理空白值时,我打算构建一些程序结构以获取唯一列表,并准备数据透视表并运行以使其具有动态性。我可以对建议的查询做同样的事情,但可能会变得冗长。有什么想法吗? – user981785