如何将sql结果条目转换为列(pivot)

时间:2016-09-29 12:05:58

标签: sql database pivot

我有桌子

| id | value   | comment   |
|--------------------------|
|  1 | Some1   | comm1     |
|--------------------------|
|  2 | Some2   | comm2     |
|--------------------------|

我有表b,表a作为外键

| id | id_a  |name    | amount    | factor   |
|--------------------------------------------|
|  1 |  1    |Car     | 12        | 2        |
|--------------------------------------------|
|  2 |  1    |Bike    | 22        | 5        |
|--------------------------------------------|
|  3 |  2    |Car     | 54        | 1        |
|--------------------------------------------|
|  4 |  2    |Bike    | 55        | 4        |
|--------------------------------------------|

结果我想要一个组合:

|id| value | comment | Car_Amount | Car_factor | Bike_Amount | Bike_Factor |
|--------------------------------------------------------------------------|
| 1| Some1 | comm1   | 12         | 2          | 22          | 5           |
|--------------------------------------------------------------------------|
| 2| Some2 | comm2   | 54         | 1          | 55          | 4           |
|--------------------------------------------------------------------------|

就我所见,这不是一个支点。但我不确定这是否是好的做法。我不是SQL的专家,但混合这样的表看起来完全错误。 我的意思是"他们"希望将其作为一个平坦的结果用于报告......

有可能吗?

感谢

3 个答案:

答案 0 :(得分:1)

SELECT t1.id,
       t1.value,
       MAX(CASE WHEN t2.name = 'Car'  THEN t2.amount END) AS Car_Amount,
       MAX(CASE WHEN t2.name = 'Car'  THEN t2.factor END) AS Car_Factor,
       MAX(CASE WHEN t2.name = 'Bike' THEN t2.amount END) AS Bike_amount,
       MAX(CASE WHEN t2.name = 'Bike' THEN t2.factor END) AS Bike_Factor
FROM a t1
INNER JOIN b t2
    ON t1.id = t2.id_a
GROUP BY t1.id

答案 1 :(得分:1)

试试这个

SELECT ID,value,comment,
       SUM(CASE WHEN Name='Car' THEN Amount END)  AS Car_Amount,
       SUM(CASE WHEN Name='Car' THEN factor END)  AS Car_factor  ,
       SUM(CASE WHEN Name='Bike' THEN Amount END)  AS Bike_Amount,
       SUM(CASE WHEN Name='Bike' THEN factor END)  AS Bike_factor 
FROM TableB
INNER JOIN TableA on  TableB.ID= TableA.id 
Group by ID,value,comment

答案 2 :(得分:1)

汇总这样的值:

select 
      a.id, a.value, a.comment,
      sum(case when b.name='Car'  then b.amount end) as Car_Amount,
      sum(case when b.name='Car'  then b.factor end) as Car_Factor,
      sum(case when b.name='Bike' then b.amount end) as Bike_Amount,
      sum(case when b.name='Bike' then b.factor end) as Bike_Factor
from a left join b on a.id=b.id_a
group by  a.id, a.value, a.comment;