在 SSMS 2016 中,我有一个带有各种连接的 select 语句,它给了我以下数据:
| box_barcode | order_number | order_shipment_id | item | qty |
|-------------|--------------|-------------------|----------|-----|
| 3330000001 | 0000105 | FP001 | tshirt-S | 1 |
| 3330000001 | 0000105 | FP001 | tshirt-M | 2 |
| 3330000001 | 0000105 | FP001 | tshirt-L | 2 |
| 3330000005 | 0000108 | FP002 | shorts-S | 2 |
| 3330000005 | 0000108 | FP002 | shorts-M | 1 |
| 3330000005 | 0000120 | FP002 | shorts-S | 1 |
| 3330000010 | 0000120 | FP003 | shirts-M | 2 |
| 3330000010 | 0000120 | FP003 | shirts-L | 2 |
| 3330000010 | 0000121 | FP003 | shirts-S | 3 |
| 3330000010 | 0000121 | FP003 | shirts-M | 3 |
| 3330000010 | 0000122 | FP003 | shirts-S | 2 |
我想添加一列来计算每个 box_barcode 的不同 order_numbers 的数量,以获得所需的结果:
| box_barcode | order_number | order_shipment_id | item | qty | count |
|-------------|--------------|-------------------|----------|-----|-------|
| 3330000001 | 0000105 | FP001 | tshirt-S | 1 | 1
| 3330000001 | 0000105 | FP001 | tshirt-M | 2 | 1
| 3330000001 | 0000105 | FP001 | tshirt-L | 2 | 1
| 3330000005 | 0000108 | FP002 | shorts-S | 2 | 2
| 3330000005 | 0000108 | FP002 | shorts-M | 1 | 2
| 3330000005 | 0000120 | FP002 | shorts-S | 1 | 2
| 3330000010 | 0000120 | FP003 | shirts-M | 2 | 3
| 3330000010 | 0000120 | FP003 | shirts-L | 2 | 3
| 3330000010 | 0000121 | FP003 | shirts-S | 3 | 3
| 3330000010 | 0000121 | FP003 | shirts-M | 3 | 3
| 3330000010 | 0000122 | FP003 | shirts-S | 2 | 3
我正在努力找出如何最好地实现这一目标。我知道 count(distinct..),但是我是否必须将当前查询放入子查询中,以便计数首先与该查询的结果相抵触?