1

是否也可以计数?我的 UNION 为我提供了所有 4 列中的所有不同值,但现在我需要知道每个值在所有 4 列中出现的次数。如果可能,需要使用库存 SQL。

在此处输入图像描述

(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

回报:

A
B
C
D
E
F
H

需要:

一个 | 3
乙 | 3C
| 4D
| 3
E | 1
楼 | 1
小时| 1

4

2 回答 2

4

SQL小提琴

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

结果

| 分类 | COLUMN_1 |
-------------------------
| 一个 | 3 |
| 乙| 3 |
| C | 4 |
| D | 3 |
| E | 1 |
| F | 1 |
| H | 1 |

当你使用时,DISTINCT你消除了额外的“A”classify3

于 2012-08-17T14:43:13.637 回答
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 
于 2012-08-17T14:36:36.097 回答