有没有一种方法可以动态获取SQL中字段的值分布?
我有一个包含250个字段的表格。我想获取每个字段的值分布:
field0
value0: 10
value1: 100
value2: 30
...
valueN: X
field1
value0: 2
value1: 124
value2: 8
...
valueN: Y
....
我知道使用case + sum可以生成此值,但随后必须将可能的值预先放入查询中:
SELECT
, Sum( Case When field0 = value0 Then 1 Else 0 End ) As [0]
, Sum( Case When field0 = value1 Then 1 Else 0 End ) As [1]
, Sum( Case When field0 = value2 Then 1 Else 0 End ) As [2]
, Sum( Case When field0 = value3 Then 1 Else 0 End ) As [3]
, Sum( Case When field0 = valueN Then 1 Else 0 End ) As [4]
FROM table
有没有办法动态地做到这一点?
答案 0 :(得分:1)
有一种方法可以使用聚合函数来获取行结果(而非列结果),例如:count
SELECT field0,
COUNT(*)
FROM table
GROUP BY field0
如果您希望在代码中得到列结果。对于某些DB品牌,它具有PIVOT功能。
答案 1 :(得分:1)
使用Postgres,您可以执行以下操作:
select t.name as column_name,
sum(val::int) as sum
from data d, jsonb_each_text(to_jsonb(d) - 'id') as t(name, val)
group by t.name;
- 'id'
从生成的JSON中删除id
属性。仅在聚合中包括某些列的另一种选择是添加一个where
条件:
select column_name,
sum(val::int) as sum
from (
select t.name as column_name,
t.val
from data d, jsonb_each_text(to_jsonb(d)) as t(name, val)
) t
where column_name like 'col%'
group by column_name;
具有以下示例表:
create table data
(
id serial primary key,
col1 int,
col2 int,
col3 int,
col4 int,
col5 int
);
insert into data (col1, col2, col3, col4, col5)
values
(1, 2, 3, 4, 5),
(6, 7, 8, 9, 10),
(11, 12, 13, 14, 15);
查询将返回:
column_name | sum
------------+----
col1 | 18
col2 | 21
col5 | 30
col4 | 27
col3 | 24