听起来您希望将数据从行转换为列。如果在 MySQL 中是这种情况,您将需要使用带有CASE
表达式的聚合函数来执行此数据转换:
Select
count(distinct case when id_type = 'a' then id end) TotalA,
count(distinct case when id_type = 'b' then id end) TotalB,
count(distinct case when id_type = 'c' then id end) TotalC
from Table
或者,如果您出于某种原因仍想使用单独的查询,那么您可以使用 aUNION ALL
然后将数据旋转到列中:
select
max(case when col = 'A' then TotalCount end) TotalA,
max(case when col = 'B' then TotalCount end) TotalB,
max(case when col = 'C' then TotalCount end) TotalC
from
(
Select count(distinct(id)) TotalCount, 'A' Col
from Table
where id_type = 'a'
union all
Select count(distinct(id)) TotalCount, 'B' Col
from Table
where id_type = 'b'
union all
Select count(distinct(id)) TotalCount, 'C' Col
from Table
where id_type = 'c'
) src