表格列标题:n,t1,t2
条目:
1 A B
2 A C
3 B C
4 D E
5 B A
如何计算每个字母出现在 t1 中的总行数减去它们出现在 t2 中的行数?我需要在 1 个查询中执行以下 2 行操作:
select count(*) as val,t1 from table group by t1
select count(*) as val,t2 from table group by t2
谢谢,马丁
表格列标题:n,t1,t2
条目:
1 A B
2 A C
3 B C
4 D E
5 B A
如何计算每个字母出现在 t1 中的总行数减去它们出现在 t2 中的行数?我需要在 1 个查询中执行以下 2 行操作:
select count(*) as val,t1 from table group by t1
select count(*) as val,t2 from table group by t2
谢谢,马丁
这是一种方法:
select t1, max(t1cnt) - max(t2cnt) as diff
from ((select t1, count(*) as t1cnt, 0 as t2cnt
from t
group by t1
) union all
(select t2, 0 as t1cnt, count(*) as t2cnt
from t
group by t2
)
) t
group by t1
使用union all
确保您从两列中获取所有可能的值,即使是仅出现在一列中的值。
您可以使用以下查询来获取结果。此查询首先获取所有不同值t1
和t2
值的列表(这是 UNION 查询)。获得这些值的列表后,您可以对发布的原始查询使用 LEFT JOIN:
select d.col, coalesce(totT1, 0) - coalesce(totT2, 0) Total
from
(
select t1 col
from entries
union
select t2 col
from entries
) d
left join
(
select count(*) totT1, t1
from entries
group by t1
) d1
on d.col = d1.t1
left join
(
select count(*) totT2, t2
from entries
group by t2
) d2
on d.col = d2.t2;