使用垂直联接SQL重组表

时间:2019-06-19 14:00:20

标签: sql postgresql

我要重组表

表A

   id      gd      gf    gt     value
|------|--------|------|-----|---------
|   1  |    M   |  1   |  5  |   2
|   1  |    F   |  1   |  5  |   6
|   1  |    M   |  6   |  10 |   15
|   1  |    F   |  6   |  10 |   17
|   1  |    M   |  11  |  15 |   22
|   1  |    F   |  11  |  15 |   3

所需的重组表

表B

  id    gd    va5    va10   va15   vatotal
|------|-----|-----|------|------|----
|   1  | M   | 2   |  15  |  22  |  39  
|   1  | F   | 6   |  17  |  3   |  26  
|      |     |     |      |      |   

我已经尝试过:

select va_5.id,va_5.gd, va5,va10,va15, sum((va5)+ (va10)+(va15))as vatotal
FROM
(SELECT
    id,
        gender,
        value as va5
FROM tableA
      WHERE gf = 1 and gt = 5) as va_5 
LEFT JOIN
(SELECT
    id,
        gender,
        value as va10
FROM tableA
      WHERE gf 6 =  and gt = 10) as va_10
     on va_5.id = val_10.id
LEFT JOIN 
(SELECT
    id,
        gender,
        value as va15
FROM tableA
      WHERE gf = 11 and gt = 15 )as va_15
       on va_15.id = va_10.id

select va_5.id,va_5.gd, va5,va10,va15, sum((va5)+ (va10)+(va15))as vatotal
FROM
(SELECT
    id,
        gender,
        value as va5
FROM tableA
      WHERE gf = 1 and gt = 5) as va_5 
LEFT JOIN
(SELECT
    id,
        gender,
        value as va10
FROM tableA
      WHERE gf 6 =  and gt = 10) as va_10
     on va_5.id = val_10.id
LEFT JOIN 
(SELECT
    id,
        gender,
        value as va15
FROM tableA
      WHERE gf = 11 and gt = 15 )as va_15
       on va_15.id = va_10.id

预期结果是这个

  id    gd    va5    va10   va15   vatotal
|------|-----|-----|------|------|----
|   1  | M   | 2   |  15  |  22  |  39  
|   1  | F   | 6   |  17  |  3   |  26  
|      |     |     |      |      |   

实际结果

   id      gd     va5    va10  va15    vatotal
|------|--------|------|-----|-------|---------
|   1  |    M   |  2   |  15 |   22  |  39
|   1  |    F   |  6   |  17 |   3   |  26
|   1  |    M   |  2   |  15 |   22  |  39
|   1  |    F   |  6   |  17 |   3   |  26
|   1  |    M   |  2   |  15 |   22  |  39
|   1  |    F   |  6   |  17 |   3   |  26

2 个答案:

答案 0 :(得分:1)

我认为您只需要条件聚合:

select a.id, a.gd, 
       max(a.value) filter (where a.gt = 5) as val_5,
       max(a.value) filter (where a.gt = 10) as val_10,
       max(a.value) filter (where a.gt = 15) as val_15,
       sum(a.value)
from tableA a 
group by a.id, a.gd;

答案 1 :(得分:0)

您的逻辑还不太清楚,但似乎您想按idgender对行进行分组。此查询应为您提供所需的内容:

select
  t5.id,
  t5.gd,
  sum(t5.value) as va5,
  sum(t10.value) as va10,
  sum(t15.value) as va15,
  sum(t5.value + t10.value + t15.value) as vatotal  
from (select * from tableA where gt = 5) t5
join (select * from tableA where gt = 10) t10 on t10.gd = t5.gd and t10.id = t5.id
join (select * from tableA where gt = 15) t15 on t15.gd = t5.gd and t15.id = t5.id
group by t5.id, t5.gd