查询以有条件地将行分发到列

时间:2015-05-27 07:39:40

标签: mysql oracle

Oracle数据库10g 10.2.0.4.0版,与Oracle SQL Developer一起使用

  

TableA - Key1 - Key2 - ConditionColumn

     

TA - K1 - K2 - C1

查询-1 SELECT K1, K2 FROM TA WHERE C1 = 1234 ORDER BY K1;

--K1 K2 --T40105 136853 --T40108 136861 --T40109 136869 --T40111 136878 --T40113 136886

  

表B - Key2 - Data1 - Data2

     

TB - K2 - D1 - D2

查询-2- SELECT K2, D1, D2 FROM TB WHERE K2 = (SELECT K2 FROM TA WHERE K1='T40105');

--K2 D1 D2 --136853 1 1554 --136853 2 1552 --136853 3 1552

对于特定的Key2,

D1总是= {1,2,3}。 如何将这两个查询组合起来获得输出,如下所示为K1的所有值?

--K1 K2 D2(@D1=1) D2(@D1=2) D2(@D1=3) --T40105 136853 1554 1552 1552 --T40108 136861 --T40109 136869 --T40111 136878 --T40113 136886

2 个答案:

答案 0 :(得分:0)

我尝试使用以下代码

select * from
(select a.k1,a.k2,b.d2,b.d1 from ta  a
left outer join
tb b
on a.k2=b.k2
)
pivot(sum(d2) as d  for (d1) in (1,2,3))
order by k1

答案 1 :(得分:0)

工作解决方案(Oracle 10g)

SELECT MAX(h.K1) AS "K1"
,b.K1 AS "K2"
,SUM(DECODE(D1,1,D2)) AS "D2(D1=1)"
,SUM(DECODE(D1,2,D2)) AS "D2(D1=2)"
,SUM(DECODE(D1,3,D2)) AS "D2(D1=3)"
FROM TB b RIGHT OUTER JOIN TA h on h.K1 = b.K1
WHERE C1 = 1234
GROUP BY b.K2
ORDER BY b.K2;