我有选择语句,如:
select trim(time), type, count(1) from table
group by trim(time),type
结果是:
02.10.13 REZ1 1
02.10.13 REZ2 5
02.10.13 REZ3 3
是否可以使用某些Oracle函数创建一些select语句以获得以下结果:
REZ1 REZ2 REZ3
1 5 3
因此,一列的结果是另一个语句中的列名,如:
select ?SOMETHING?
from (
select trim(time), type, count(1)
from table
group by trim(time),type) s
答案 0 :(得分:1)
WITH t(l_date, val, l_count)
AS
(SELECT to_date('02.10.13', 'dd.mm.yy'), 'REZ1' , 1 FROM dual UNION
SELECT to_date('02.10.13', 'dd.mm.yy'), 'REZ2' , 5 FROM dual UNION
SELECT to_date('02.10.13', 'dd.mm.yy'), 'REZ3' , 3 FROM dual
)
SELECT *
FROM
( SELECT val, l_count FROM t
) PIVOT (MAX(l_count) FOR (val) IN ('REZ1' REZ1,'REZ2' REZ2 ,'REZ3' REZ3));
答案 1 :(得分:0)
也许你可以为此尝试SQL替代方案:
SELECT MAX(CASE type
WHEN 'REZ1' THEN cnt
ELSE NULL
END) AS REZ1,
MAX(CASE type
WHEN 'REZ2' THEN cnt
ELSE NULL
END) AS REZ2,
MAX(CASE type
WHEN 'REZ3' THEN cnt
ELSE NULL
END) AS REZ3
FROM (SELECT trim(time), type, count(1) as cnt FROM table
GROUP BY trim(time), type);
甚至更好:
SELECT COUNT(CASE type
WHEN 'REZ1' THEN 1
ELSE NULL
END) AS REZ1,
COUNT(CASE type
WHEN 'REZ2' THEN 1
ELSE NULL
END) AS REZ2,
COUNT(CASE type
WHEN 'REZ3' THEN 1
ELSE NULL
END) AS REZ3
FROM table;
输出:
REZ1 | REZ2 | REZ3
1 | 5 | 3
当您知道type
列中的值时,此选项适用。即使是{11}中可用的pivot
,也要求您知道列中的值,以便按照ajmalmhd04的答案中所述进行转动。
答案 2 :(得分:0)
假设第二列不具有除REZ1..3之外的任何值,则以下解决方案将转置表数据并通过累加值来处理重复。
WITH t
AS (SELECT TO_DATE ('02.10.13', 'dd.mm.yy') AS dt,
'REZ1' AS typ,
1 AS cnt
FROM DUAL
UNION
SELECT TO_DATE ('02.10.13', 'dd.mm.yy') AS dt,
'REZ2' AS typ,
5 AS cnt
FROM DUAL
UNION
SELECT TO_DATE ('02.10.13', 'dd.mm.yy') AS dt,
'REZ3' AS typ,
3 AS cnt
FROM DUAL
UNION
SELECT TO_DATE ('03.10.13', 'dd.mm.yy') AS dt,
'REZ1' AS typ,
7 AS cnt
FROM DUAL
UNION
SELECT TO_DATE ('03.10.13', 'dd.mm.yy') AS dt,
'REZ2' AS typ,
2 AS cnt
FROM DUAL)
SELECT dt,
SUM (CASE WHEN typ = 'REZ1' THEN cnt ELSE 0 END) AS "REZ1",
SUM (CASE WHEN typ = 'REZ2' THEN cnt ELSE 0 END) AS "REZ2",
SUM (CASE WHEN typ = 'REZ3' THEN cnt ELSE 0 END) AS "REZ3"
FROM t
GROUP BY dt;
DT REZ1 REZ2 REZ3
--------- ---------- ---------- ----------
02-OCT-13 1 5 3
03-OCT-13 7 2 0
2 rows selected.
Incase列#2将具有随机值,可能需要使用某种游标来调整此查询以考虑动态列。 如果我能够设计出来,我会尝试发布。
答案 3 :(得分:0)
select trim(time),
count(decode(type, 'REZ1', 1)) AS REZ1,
count(decode(type, 'REZ2', 1)) AS REZ2,
count(decode(type, 'REZ3', 1)) AS REZ3
from table
group by trim(time)