0

表格列标题: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

谢谢,马丁

4

2 回答 2

3

这是一种方法:

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确保您从两列中获取所有可能的值,即使是仅出现在一列中的值。

于 2013-05-27T15:54:55.747 回答
3

您可以使用以下查询来获取结果。此查询首先获取所有不同值t1t2值的列表(这是 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;

请参阅带有演示的 SQL Fiddle

于 2013-05-27T15:57:13.693 回答