根据第一栏中的唯一值计算第二栏中的值出现

时间:2019-10-09 19:06:58

标签: sql oracle pivot

Oracle SQL中的此表给出了最简单的解释方法。

+-----------------+------------+
| COUNTRY         | VALUE      |  
+-----------------+------------+
| England         | A          |
| England         | A          |
| England         | A          |
| England         | B          |
| England         | B          |
| France          | A          |
| France          | A          |
| France          | B          |
+-----------------+------------+

我将如何产生此结果,即COUNTRY列中唯一值的A和B的计数

+-----------+------------+------------+
| COUNTRY   | COUNT(A)   | COUNT(B)   |   
+-----------+------------+------------+
| England   | 3          | 2          |
| France    | 2          | 1          |
+-----------+------------+------------+

我确定这已经得到回答,我只是不知道该怎么问。 谢谢

2 个答案:

答案 0 :(得分:1)

gamma

是条件聚合的一个例子

答案 1 :(得分:0)

使用PIVOT

Oracle设置

CREATE TABLE table_name ( COUNTRY, VALUE ) AS
SELECT 'England', 'A' FROM DUAL UNION ALL
SELECT 'England', 'A' FROM DUAL UNION ALL
SELECT 'England', 'A' FROM DUAL UNION ALL
SELECT 'England', 'B' FROM DUAL UNION ALL
SELECT 'England', 'B' FROM DUAL UNION ALL
SELECT 'France',  'A' FROM DUAL UNION ALL
SELECT 'France',  'A' FROM DUAL UNION ALL
SELECT 'France',  'B' FROM DUAL;

查询

SELECT *
FROM   table_name
PIVOT ( COUNT(*) FOR value IN ( 'A' AS "COUNT(A)", 'B' AS "COUNT(B)" ) )

输出

COUNTRY | COUNT(A) | COUNT(B)
:------ | -------: | -------:
England |        3 |        2
France  |        2 |        1

db <>提琴here