在SQL中将多个列视为1以获取聚合

时间:2012-08-17 14:34:31

标签: sql unions

是否有可能获得数量?我的UNIONs为我提供了所有4列的所有不同值,但现在我需要知道每个值在所有4列中出现的次数。如果可能的话,需要继续使用库存SQL。

enter image description here

(SELECT DISTINCT classify1 AS classified FROM class) UNION
(SELECT DISTINCT classify2 AS classified FROM class) UNION
(SELECT DISTINCT classify3 AS classified FROM class) UNION
(SELECT DISTINCT classify4 AS classified FROM class)
ORDER BY classified

返回:

一个

ç
d
Ë
˚F
ħ

需要:

A | 3
B | 3
C | 4
D | 3
E | 1
F | 1
H | 1个

2 个答案:

答案 0 :(得分:4)

SQL Fiddle

SELECT a.classified, COUNT(*)
FROM
(
  (SELECT classify1 AS classified FROM class) UNION ALL
  (SELECT classify2 AS classified FROM class) UNION ALL
  (SELECT classify3 AS classified FROM class) UNION ALL
  (SELECT classify4 AS classified FROM class)) a
GROUP BY a.classified

结果

| CLASSIFIED | COLUMN_1 |
-------------------------
|          A |        3 |
|          B |        3 |
|          C |        4 |
|          D |        3 |
|          E |        1 |
|          F |        1 |
|          H |        1 |

当您使用DISTINCT时,您会消除classify3

中的额外“A”

答案 1 :(得分:0)

使用UNION ALL代替UNION,将结果嵌入子查询中以执行聚合。

SELECT
  classified,
  COUNT(*)
FROM
(
  (SELECT classify1 AS classified FROM class) UNION ALL
  (SELECT classify2 AS classified FROM class) UNION ALL
  (SELECT classify3 AS classified FROM class) UNION ALL
  (SELECT classify4 AS classified FROM class)
)
  AS unified_data
GROUP BY
  classified
ORDER BY
  classified