急~~~~~~~~~高手请帮忙,求一sql语句 把字段值横放
高手请帮忙,求一sql语句 把字段值横放
表如下
table(id,A,B) id,A,B为字段名
------------------
id ¦A ¦ B ¦
1 0.1 ¦ 10 ¦
1 0.2 ¦ 13 ¦
1 0.3 ¦ 12 ¦
2 0.4 ¦ 12 ¦
2 0.5 ¦ 12 ¦
2 0.6 ¦ 12 ¦
通过sql后表数剧变成(通过ID,把A,B字段横放了)
1 ¦ 0.1 ¦ 0.2 ¦0.3 ¦ 10 ¦ 13 ¦12
2 ¦ 0.4 ¦ 0.5 ¦ 0.6 ¦ 12 ¦ 12 ¦12
A,B列的值成一个字段~~
最好不用函数,用查询
------解决方案--------------------如果A,B字段均为数值型,且固定为3的话,那么可以考虑以下做法:
SELECT A.ID,
(SELECT MIN(A) FROM AAA WHERE ID = A.ID) AS COL_1,
(SELECT (SUM(A) - MAX(A) - MIN(A)) FROM AAA WHERE ID = A.ID) AS COL_2,
(SELECT MAX(A) FROM AAA WHERE ID = A.ID) AS COL_3,
(SELECT MIN(B) FROM AAA WHERE ID = A.ID) AS COL_4,
(SELECT (SUM(B) - MAX(B) - MIN(B)) FROM AAA WHERE ID = A.ID) AS COL_5,
(SELECT MAX(B) FROM AAA WHERE ID = A.ID) AS COL_6
FROM AAA A
GROUP BY ID
------解决方案--------------------哦,这样写更好:
SELECT A.ID,
MIN(A) AS COL_1,(SUM(A) - MAX(A) - MIN(A)) AS COL_2,MAX(A) AS COL_3,
MIN(B) AS COL_4,(SUM(B) - MAX(B) - MIN(B)) AS COL_5,MAX(B) AS COL_6
FROM AAA A
GROUP BY ID
------解决方案--------------------select
id,
sum(decode(rn,1,A)),
sum(decode(rn,2,A)),
sum(decode(rn,3,A)),
sum(decode(rn,1,B)),
sum(decode(rn,2,B)),
sum(decode(rn,3,B))
from
(
select row_number() over (partition by id order by id) rn,t.*
from AAA
)
group by id