3

我需要编写一个语句来显示表中的每一列、填充该列的记录的计数和百分比,以及不同的值计数。

例如,如果我有一个表地址包含:

Addr1 | AddrText  | PostalCode
11111 | demo ave  | 91210
22222 | demo2 ave | null
33333 | null      | null

它应该显示如下内容:

columns    | Count | Percentage
Addr1      | 3     | 100
AddrText   | 2     | 66.6
PostalCode | 1     | 33.3

或者让列保持不变,只将数据作为行,但我认为上面可能更容易。

ps:很抱歉,如果我无法正确格式化,但我希望你能明白。

4

2 回答 2

3

您可以使用然后应用聚合函数来取消透视列以获取计数和百分比:UNION ALL

select col,
  count(case when col is not null and value is not null then 1 end) CntCol,
  (count(case when col is not null and value is not null 
         then 1 end) / count(col))*100.0 Percentage
from
(
  select 'Addr1' col, Addr1 value
  from yourtable
  union all 
  select 'AddrText' col, AddrText value
  from yourtable
  union all 
  select 'PostalCode' col, PostalCode value
  from yourtable
) src
group by col

请参阅带有演示的 SQL Fiddle

结果是:

|        COL | CNTCOL | PERCENTAGE |
------------------------------------
|      Addr1 |      3 |        100 |
|   AddrText |      2 |   66.66667 |
| PostalCode |      1 |   33.33333 |
于 2013-01-17T00:58:54.940 回答
0
SELECT 'Addr1' col, 
       COUNT(Addr1) cntcol, COUNT(addr1)/count(*) percentage
FROM yourtable
union all
SELECT 'AddrText' col, 
       COUNT(AddrText) cntcol, COUNT(AddrText)/count(*) percentage
FROM yourtable
union all
SELECT 'PostalCode' col, 
       COUNT(PostalCode) cntcol, COUNT(PostalCode)/count(*) percentage
FROM yourtable
于 2013-01-17T01:05:04.373 回答