I'm a bit of a beginner in sql and I need your help. I'm sorry that I don't know if the question is correct.
now the code gives this;
--------- ---------- ------------- ------------
| id | CompanyId| DealId | price |
--------- ---------- ------------- ------------
| 1 | 1 | 1 | 100 |
| 2 | 1 | 2 | 50 |
| 3 | 1 | 3 | 25 |
| 4 | 2 | 1 | 1000 |
| 5 | 2 | 2 | 2000 |
| 6 | 2 | 3 | 2500 |
--------- ---------- ------------- ------------
but this is what i want;
--------- ---------- ------------- ------------ ------------ --
| id | companyId| DealName1 | DealName2 | DealName3 | |
--------- ---------- ------------- ------------ ------------ --
| 1 | 1 | 100 | 50 | 25 | |
| 2 | 2 | 1000 | 2000 | 2500 | |
| 3 | 3 | value | value | value | |
| 4 | 4 | value | value | value | |
--------- ---------- ------------- ------------ ------------ --
CodePudding user response:
select CompanyId
,[1] as DealName1
,[2] as DealName2
,[3] as DealName3
from (select CompanyId, DealId, price from t) t
pivot (sum(price) for DealId in([1],[2],[3])) p
CompanyId | DealName1 | DealName2 | DealName3 |
---|---|---|---|
1 | 100 | 50 | 25 |
2 | 1000 | 2000 | 2500 |