0

我有两个这样的事务表:

TableA

 X  R  S
 71 1 10 
 71 2 20
 71 3 30 
 72 1 40 
 72 2 50
 72 3 60

TableB


 X  P Q
 71 1 110 
 71 2 120
 71 3 130 
 73 1 140 
 73 2 150
 73 3 160

我想展平表格并执行一个查询,结果如下:

  X  S1  S2  S3   Q1  Q2  Q3

  71 10  20  30  110 120 130
  72 40  50  60   0    0   0
  73  0   0   0  140 150 160

其中 S 和 Q 中的下标表示当第二列等于下标时第三列的值。例如,S1 表示S第二列等于 1 时的列值,或者 Q2 表示Q第二列为 2 时的值。

我不知道什么是最好的方法。也许我可以使用 case 语句或者可能是子查询。但老实说,我没有具体的想法。

4

2 回答 2

2

你会想用一个连接和两个聚合来做到这一点:

select coalesce(a.x, b.x) as x, a.s1, a.s2, a.s3, b.q1, b.q2, b.q3
from (select x,
             max(case when r = 1 then s end) as s1,
             max(case when r = 2 then s end) as s2,
             max(case when r = 3 then s end) as s3
      from tableA a
      group by x
     ) a full outer join
     (select x,
             max(case when p = 1 then q end) as q1,
             max(case when p = 2 then q end) as q2,
             max(case when p = 3 then q end) as q3
      from tableb b
      group by x
     ) b
     on a.x = b.x;

编辑:

如果要避免嵌套子查询,可以尝试:

select coalesce(a.x, b.x) as x,
       max(case when r = 1 then s end) as s1,
       max(case when r = 2 then s end) as s2,
       max(case when r = 3 then s end) as s3
       max(case when p = 1 then q end) as q1,
       max(case when p = 2 then q end) as q2,
       max(case when p = 3 then q end) as q3
from TableA a full outer join
     TableB b
     on a.x = b.x and a.r = b.p
group by coalesce(a.x, b.x);

它甚至可能更有效。

于 2013-08-28T01:39:24.103 回答
0
SELECT 
ISNULL(A.x, B.x) AS x, SUM(CASE WHEN R = 1 THEN S ELSE 0 END) AS S1,
SUM(CASE WHEN R = 2 THEN S ELSE 0 END) AS S2,
SUM(CASE WHEN R = 3 THEN S ELSE 0 END) AS S3,
SUM(CASE WHEN P = 1 THEN Q ELSE 0 END) AS Q1,
SUM(CASE WHEN P = 2 THEN Q ELSE 0 END) AS Q2,
SUM(CASE WHEN P = 3 THEN Q ELSE 0 END) AS Q3 
FROM tableA A FULL JOIN tableB B ON A.X = B.X
GROUP BY ISNULL(A.x, B.x)

T-SQL 版本

于 2013-08-28T01:40:12.417 回答