sql-server 如何在sql中列出每个类别下的产品?

ddrv8njm  于 2022-10-31  发布在  其他
关注(0)|答案(1)|浏览(94)

我是一个SQL初学者,我需要你的帮助。很抱歉,我不知道这个问题是否正确。
现在代码给出了这个;

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

但这是我想要的

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

wd2eg0qa1#

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

| 公司ID|交易名称1|交易名称2|交易名称3|
| - -|- -|- -|- -|
| 一个|100个|五十个|二十五个|
| 2个|千元|二○ ○ ○年|小行星2500|
Fiddle

相关问题