、私は様々でselect文を持っているが、私に次のようなデータを与える加入:列Yに基づく列Xの個別値の数をカウントする列? SSMS 2016年に
| 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 ..)を知っていますが、最初のクエリの結果と逆になるように、現在のクエリをサブクエリに入れる必要がありますか?
はい。各box_barcodeの数を取得し、それをテーブルに結合します。あなたは 'count'ウィンドウ関数でそれをやっていた可能性がありますが、' distinct'をサポートしていません。 –
私は、共通テーブル式を使用してbox_barcodeごとに異なる注文番号の数を計算し、次にCTEをクエリに結合し、その値をSELECTステートメントのパラメータとして表示します。あなたがViewへの結合の束であなたの全体のクエリを作るなら、それは少しきれいに見えます。 – EMUEVIL