How rotate sql result entries into columns (pivot)

2019-02-27 02:13发布

I have table a

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

and i have table b with table a as foreign key

| 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        |
|--------------------------------------------|

As result I want to have a combination:

|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           |
|--------------------------------------------------------------------------|

It is not a pivot as far as I can see. But I am not sure if this is good practise at all. I am not an expert in SQL things, but it looks utterly wrong to mix tables like that. I mean "they" want to have it as a flat result to use it for reporting...

Is it possible at all?

thanks

3条回答
不美不萌又怎样
2楼-- · 2019-02-27 02:35

Aggregate values like this:

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;
查看更多
仙女界的扛把子
3楼-- · 2019-02-27 02:38
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
查看更多
何必那么认真
4楼-- · 2019-02-27 02:41

Try this

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
查看更多
登录 后发表回答