2017-06-07 2 views
0

、私は様々で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 ..)を知っていますが、最初のクエリの結果と逆になるように、現在のクエリをサブクエリに入れる必要がありますか?

+0

はい。各box_barcodeの数を取得し、それをテーブルに結合します。あなたは 'count'ウィンドウ関数でそれをやっていた可能性がありますが、' distinct'をサポートしていません。 –

+0

私は、共通テーブル式を使用してbox_barcodeごとに異なる注文番号の数を計算し、次にCTEをクエリに結合し、その値をSELECTステートメントのパラメータとして表示します。あなたがViewへの結合の束であなたの全体のクエリを作るなら、それは少しきれいに見えます。 – EMUEVIL

答えて

1

つ以上のオプション。

select t.*, 
     max(rnk) over(partition by box_barcode) as distinct_count 
from (select t.*, 
     dense_rank() over(partition by box_barcode order by order_numbers) as rnk 
     from t 
    ) t 

最も高いランクの行(dense_rankを使用)は、box_barcodeあたりのオーダー番号の明確な数になります。

+0

これはうまくいった。ご協力いただき誠にありがとうございます! – Smeghead

1

また、SQL Serverはウィンドウ機能としてcount(distinct)をサポートしていません。しかし、エミュレートするのは簡単です:dense_rankmax

select t.*, 
     sum(case when seqnum = 1 then 1 else 0 end) over (partition by box_barcode) as distinct_count 
from (select t.*, 
      row_number() over (partition by box_barcode, order_numbers order by box_barcode) as seqnum 
     from t 
    ) t; 
+0

'sum'に' over'句を忘れている必要があります。 –

+0

@vkp。 。 。ありがとうございました。 –

+0

ありがとうございます。 – Smeghead

関連する問題