编写高级 SQL Select

2022-01-22 00:00:00 pivot sql tsql sql-server

物品表:

|   Item    |   Qnty    |   ProdSched   |
|    a      |    1      |       1       |
|    b      |    2      |       1       |
|    c      |    3      |       1       |
|    a      |    4      |       2       |
|    b      |    5      |       2       |
|    c      |    6      |       2       |

有没有办法使用 SQL SELECT 像这样输出它?

Is there a way I can output it like this using SQL SELECT?

|   Item    |   ProdSched(1)(Qnty)  |   ProdSched(2)(Qnty)  |
|    a      |           1           |       4               |
|    b      |           2           |       5               |
|    c      |           3           |       6               |

推荐答案

SELECT Item, 
  [ProdSched(1)(Qnty)] = MAX(CASE WHEN ProdSched = 1 THEN Qnty END),
  [ProdSched(2)(Qnty)] = MAX(CASE WHEN ProdSched = 2 THEN Qnty END)
FROM dbo.tablename
GROUP BY Item
ORDER BY Item;

相关文章