SQL 查询以显示列中的 table 列项目?
SQL Query to display table columns items in a column?
我在数据库中有一个 table,如下所示:
-----------------------------
| ID | Item1 | Item2 | Item3|
-----------------------------
| 1 | A1 | B3 | C1 |
| 2 | A2 | B3 | C2 |
| 3 | A1 | B2 | C2 |
| 4 | A2 | B1 | C1 |
-----------------------------
我想显示 table 个项目,其计数如下:
---------------
| item | count|
---------------
| A1 | 2 |
| A2 | 2 |
| B1 | 1 |
| B2 | 1 |
| B3 | 2 |
| C1 | 2 |
| C2 | 2 |
---------------
可能吗?如果是,查询如何?到目前为止,我只能像这样为每个项目一一显示它:
------------------
| Item1 | Count |
------------------
SELECT COUNT(*) AS `Count` , `Item1` FROM `table` GROUP BY `Item1`;
------------------
| Item2 | Count |
------------------
SELECT COUNT(*) AS `Count` , `Item2` FROM `table` GROUP BY `Item2`;
------------------
| Item3 | Count |
------------------
SELECT COUNT(*) AS `Count` , `Item3` FROM `table` GROUP BY `Item3`;
使用union all
和group by
:
select item, count(*)
from ((select item1 as item from `table`) union all
(select item2 as item from `table`) union all
(select item3 as item from `table`)
) t
group by item
order by item;
我在数据库中有一个 table,如下所示:
-----------------------------
| ID | Item1 | Item2 | Item3|
-----------------------------
| 1 | A1 | B3 | C1 |
| 2 | A2 | B3 | C2 |
| 3 | A1 | B2 | C2 |
| 4 | A2 | B1 | C1 |
-----------------------------
我想显示 table 个项目,其计数如下:
---------------
| item | count|
---------------
| A1 | 2 |
| A2 | 2 |
| B1 | 1 |
| B2 | 1 |
| B3 | 2 |
| C1 | 2 |
| C2 | 2 |
---------------
可能吗?如果是,查询如何?到目前为止,我只能像这样为每个项目一一显示它:
------------------
| Item1 | Count |
------------------
SELECT COUNT(*) AS `Count` , `Item1` FROM `table` GROUP BY `Item1`;
------------------
| Item2 | Count |
------------------
SELECT COUNT(*) AS `Count` , `Item2` FROM `table` GROUP BY `Item2`;
------------------
| Item3 | Count |
------------------
SELECT COUNT(*) AS `Count` , `Item3` FROM `table` GROUP BY `Item3`;
使用union all
和group by
:
select item, count(*)
from ((select item1 as item from `table`) union all
(select item2 as item from `table`) union all
(select item3 as item from `table`)
) t
group by item
order by item;