表T1有3列,C1,C2和C3,其值为R,G,B
C1 C2 C3
R R R
R R R
G R R
G G R
B G B
B B B
我想在下面的结构中添加一个新表:
R G B
9 4 5
在上表中,表T1的不同值必须显示为列名,并且必须显示整个表中R,G,B值的总数。
答案 0 :(得分:0)
在每个列上使用COUNT
聚合函数并使用CASE
表达式按正确的字符值进行过滤:
Oracle和/或MS SQL Server安装程序:
CREATE TABLE table_name(
C1 CHAR(1),
C2 CHAR(1),
C3 CHAR(1)
);
INSERT INTO table_name VALUES ( 'R', 'R', 'R' );
INSERT INTO table_name VALUES ( 'R', 'R', 'R' );
INSERT INTO table_name VALUES ( 'G', 'R', 'R' );
INSERT INTO table_name VALUES ( 'G', 'G', 'R' );
INSERT INTO table_name VALUES ( 'B', 'G', 'B' );
INSERT INTO table_name VALUES ( 'B', 'B', 'B' );
查询1 :
SELECT COUNT( CASE C1 WHEN 'R' THEN 1 END )
+ COUNT( CASE C2 WHEN 'R' THEN 1 END )
+ COUNT( CASE C3 WHEN 'R' THEN 1 END ) AS R,
COUNT( CASE C1 WHEN 'G' THEN 1 END )
+ COUNT( CASE C2 WHEN 'G' THEN 1 END )
+ COUNT( CASE C3 WHEN 'G' THEN 1 END ) AS G,
COUNT( CASE C1 WHEN 'B' THEN 1 END )
+ COUNT( CASE C2 WHEN 'B' THEN 1 END )
+ COUNT( CASE C3 WHEN 'B' THEN 1 END ) AS B
FROM table_name
<强> Results 强>:
| R | G | B |
|---|---|---|
| 9 | 4 | 5 |
查询2 ,或者您可以使用UNPIVOT
:
SELECT COUNT( CASE value WHEN 'R' THEN 1 END ) AS R,
COUNT( CASE value WHEN 'G' THEN 1 END ) AS G,
COUNT( CASE value WHEN 'B' THEN 1 END ) AS B
FROM table_name
UNPIVOT ( value FOR id IN ( C1, C2, C3 ) ) AS u -- Do not need AS keyword in Oracle
<强> Results 强>:
| R | G | B |
|---|---|---|
| 9 | 4 | 5 |