显示表中的所有列以及每列中的已填充记录数

时间:2013-01-17 00:53:00

标签: mysql sql unpivot

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

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

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:很抱歉,如果我无法正确格式化,但我希望你明白这一点。

2 个答案:

答案 0 :(得分: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 with Demo

结果是:

|        COL | CNTCOL | PERCENTAGE |
------------------------------------
|      Addr1 |      3 |        100 |
|   AddrText |      2 |   66.66667 |
| PostalCode |      1 |   33.33333 |

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