这应该相当简单,但我找不到我需要的确切语法。我有一个具有name1和name2字段的表。我只想要一个字段中所有唯一值的列表以及每个值的计数。例如:
name1 name2
-----------------
smith jones
jones williams
evans williams
elliot james
williams smith
我想要:
name count
--------------
smith 2
jones 2
Williams 3
evans 1
Elliot 1
james 1
要获取我使用联合查询的唯一名称:
select name1 as myname
from myTable
union
select name2 as myname
from myTable
但我无法找到计数所在位置的正确语法。有人可以把我从痛苦中解救出来吗?
答案 0 :(得分:6)
您应该使用UNION ALL而不是UNION,因为UNION将删除所有重复项,而UNION ALL则不会。然后,您可以将union查询用作子查询,并执行计数:
SELECT name, COUNT(*)
FROM
(SELECT name1 name FROM tablename
UNION ALL
SELECT name2 name FROM tablename) s
GROUP BY
name
请参阅小提琴here。
答案 1 :(得分:2)
您可以使用union all
:
select name, count(*) as cnt
from ((select name1 as name from t) union all
(select name2 from t)
) t
group by name;
使用union all
代替union
非常重要。后者删除了你不想要的重复项。
对于此类较大的查询,使用unpivot
或以下构造更有效:
select (case when n.n = 1 then name1 else name2 end) as name, count(*)
from t cross join
(select 1 as n union all select 2) n
group by (case when n.n = 1 then name1 else name2 end)
union all
查询将扫描表格两次。此版本通常只扫描一次表。
答案 2 :(得分:1)
select t.name,count(t.name) count
from
(
select name1 as name from tbl
union all
select name2 as name from tbl
)t
group by t.name
<强> SQL Fiddle 强>
答案 3 :(得分:1)
解决此类问题的另一种典型方法是使用 和 语法:
-- Put here whatever entangled query you have and mark it "with"
with myQuery as
(select name1 as myName
from myTable
union all
select name2 as myName
from myTable)
-- And now do everything you want with myQuery, as if it's an ordinary table
select myName as Name,
Count(*)
from myQuery
group by myName