1

考虑一个跟踪维修的系统。我有一个包含客户数据和一个通用 ID 键的表。我有第二个表,其中有一列显示每个 id 键上使用了哪种类型的修复部件以及使用了多少。它们的定义如下:

order_information
order_id  |  cust_last_name
465          Smith
899          Williams
512          Johnson
345          Fenton
122          Bowles
944          Cooper

parts_usage
order_id  |  part_type  |  part_quantity
465          Part 1        5
465          Part 2        4
899          Part 1        2
899          Part 2        8
899          Part 3        6
512          Part 3        1
345          Part 2        4
345          Part 3        5
122          Part 2        3
944          Part 1        2

我想运行一个报告查询,该查询将返回零件的分解如下:

order_id  |  Part 1  |  Part 2  |  Part 3  |  Total
465          5          4                     9
899          2          8          6          16
512                                1          1
345                     4          5          9
122                     3                     3
944          2                                2

是否可以通过查询来执行此操作,以便我的报告可以显示每个维修票上使用了每个零件的数量?

如您所见,每个都order_id可以有多种零件类型和唯一数量。我想将不同的部分类型(我总共有 3 个)分成 3 个单独的列,它们的总数由order_id.

4

1 回答 1

1
select order_id, [Part 1], [Part 2], [Part 3], Total
from 
(
  select oi.order_id
    , part_type
    , part_quantity
    , Total = sum(part_quantity) over (partition by oi.order_id)
  from order_information oi
    inner join parts_usage pu on oi.order_id = pu.order_id
) as parts
pivot 
(
  sum(part_quantity) for part_type in ([Part 1], [Part 2], [Part 3])
) as pvt
order by order_id

This works for me.

I have ordered the resultset by order_id as well; there doesn't appear to be a specific order in your example results but it is mentioned in the question details.

You can see the key is to combine the PIVOT with a SUM aggregate window function.

SQL Fiddle with demo.

于 2013-06-11T20:57:43.340 回答