如何将常量值更改为 SQL 中的列 header?
How do I change a constant value to a column header in SQL?
SQL查询:
select type,count(*), 'Active'
from file where removed = '0'
union all
select type,count(*), 'Removed'
from file where removed = '1'
给出:
TYPE COUNT ( * ) Constant value
A 24,168 Active
A 1 Removed
B 8,280 Active
B 1,263 Removed
但是,我怎样才能将 SQL 更改为:
TYPE Active Removed
A 24,168 1
B 8,280 1,263
补充可选问题:包含以下总数的最佳方法是什么?
TYPE Active Removed
A 24,168 1
B 8,280 1,263
Total 32,448 1,264
这是我对补充的最佳回答,如果您发现任何不足或改进,请告诉我:
select
type,
sum(CASE WHEN removed = '0' THEN 1 ELSE 0 END) 'Active',
sum(CASE WHEN removed = '1' THEN 1 ELSE 0 END) 'Removed'
from file
Group by type
union all
select 'Total',
sum(CASE WHEN removed = '0' THEN 1 ELSE 0 END) 'Active',
sum(CASE WHEN removed = '1' THEN 1 ELSE 0 END) 'Removed'
from file
感谢所有发表评论或回答的人,感谢您的帮助。
使用case
表达式做条件聚合:
select type,
count(case when removed = '0' then 1 end) as "Active",
count(case when removed = '1' then 1 end) as "Removed"
from file
group by type
如果有很多行除 0/1 以外的其他删除值,并且该列已编入索引,则可以抛出一个
WHERE removed IN ('0','1')
加快速度!
你可以试试:
select
type,
sum(CASE WHEN removed = '0' THEN 1 ELSE 0 END) 'Active',
sum(CASE WHEN removed = '1' THEN 1 ELSE 0 END) 'Removed'
from file
Group by type
为了在没有 union
的情况下得到答案的总数,请尝试:
select
coalesce(type, 'Totals') type,
sum(CASE WHEN removed = '0' THEN 1 ELSE 0 END) Active,
sum(CASE WHEN removed = '1' THEN 1 ELSE 0 END) Removed
from file
Group by rollup(type)
这适用于 v6.1 及更高版本。
SQL查询:
select type,count(*), 'Active'
from file where removed = '0'
union all
select type,count(*), 'Removed'
from file where removed = '1'
给出:
TYPE COUNT ( * ) Constant value
A 24,168 Active
A 1 Removed
B 8,280 Active
B 1,263 Removed
但是,我怎样才能将 SQL 更改为:
TYPE Active Removed
A 24,168 1
B 8,280 1,263
补充可选问题:包含以下总数的最佳方法是什么?
TYPE Active Removed
A 24,168 1
B 8,280 1,263
Total 32,448 1,264
这是我对补充的最佳回答,如果您发现任何不足或改进,请告诉我:
select
type,
sum(CASE WHEN removed = '0' THEN 1 ELSE 0 END) 'Active',
sum(CASE WHEN removed = '1' THEN 1 ELSE 0 END) 'Removed'
from file
Group by type
union all
select 'Total',
sum(CASE WHEN removed = '0' THEN 1 ELSE 0 END) 'Active',
sum(CASE WHEN removed = '1' THEN 1 ELSE 0 END) 'Removed'
from file
感谢所有发表评论或回答的人,感谢您的帮助。
使用case
表达式做条件聚合:
select type,
count(case when removed = '0' then 1 end) as "Active",
count(case when removed = '1' then 1 end) as "Removed"
from file
group by type
如果有很多行除 0/1 以外的其他删除值,并且该列已编入索引,则可以抛出一个
WHERE removed IN ('0','1')
加快速度!
你可以试试:
select
type,
sum(CASE WHEN removed = '0' THEN 1 ELSE 0 END) 'Active',
sum(CASE WHEN removed = '1' THEN 1 ELSE 0 END) 'Removed'
from file
Group by type
为了在没有 union
的情况下得到答案的总数,请尝试:
select
coalesce(type, 'Totals') type,
sum(CASE WHEN removed = '0' THEN 1 ELSE 0 END) Active,
sum(CASE WHEN removed = '1' THEN 1 ELSE 0 END) Removed
from file
Group by rollup(type)
这适用于 v6.1 及更高版本。