开发者

How to use PIVOT clause over blank values

开发者 https://www.devze.com 2023-04-12 16:27 出处:网络
Sample data: Data table1: prodidtype location(there are more columns, just ignoring them for this example)

Sample data:

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

The problem am facing is with the blank values in the loc开发者_如何学Pythonation field. I donno how to represent the blank location values in the pivot query.

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. 


How about just swapping out the null/blank locations for a dummy value. So change

select type, location from table1

to

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

Then the column will be zz or whatever dummy value you choose


You could just abandon PIVOT and use

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
0

精彩评论

暂无评论...
验证码 换一张
取 消