1

ピボットテーブルを作成するのに本当に役立つことができました。一部の行にデータがあり、代わりに列に表示する必要があり、他のレコードの値の隣に並置されています。現在、データは次の形式になっています。

Region  |  Location  |  Customer | CustomerKey |Status
North   |  New York  |  John     | 111         |Active
North   |  New York  |  Mary     | 112         |Active
North   |  Delaware  |  Bob      | 113         |Idle
North   |  New Jersey|  Bob      | 113         |Active
West    |  California|  Bob      | 113         |Inactive
West    |  Washington|  Greg     | 114         |Inactive
West    |  Utah      |  Tim      | 115         |Active
North   | All States |  Bob      | 113         |VIP Customer
North   | All States |  Mary     | 112         |Regular Customer
West    | All States |  Bob      | 113         |Regular Customer
West    | All States |  Tim      | 115         |Regular Customer
West    | All States |  Greg     | 114         |VIP Customer
North   | All States |  John     | 111         |Regular Customer

問題は、[ステータス] 列にあり、1 つのグループの値 (非アクティブ/アクティブ/アイドル) と別のグループ (VIP 顧客と通常の顧客) を持つことができます。[場所] 列が [すべての州] の場合、VIP/通常の値が使用されます。次の行に沿ってデータを表示するために、列を追加したいと思います。

Region  |  Location  |  Customer | CustomerKey |Status   | VIPStatus
North   |  New York  |  John     | 111         |Active   | No
North   |  New York  |  Mary     | 112         |Active   | No
North   |  Delaware  |  Bob      | 113         |Idle     | Yes
North   |  New Jersey|  Bob      | 113         |Active   | Yes
West    |  California|  Bob      | 113         |Inactive | No
West    |  Washington|  Greg     | 114         |Inactive | Yes
West    |  Utah      |  Tim      | 115         |Active   | No

基本的に、顧客が「VIP 顧客」のステータスを持つレコードを持っている場合、地域と対応する場所の値「すべての州」の組み合わせの下で、「VIPStatus」が「はい」または「いいえ」と表示されます。 ' その特定の地域でのその顧客の記録の下 (場所の状態に関係なく)。これに対する簡単な解決策はありますか?このデータを T-SQL で再配置する際の助けをいただければ幸いです。

4

1 に答える 1

3

必要な結果を得るには、テーブルに複数回参加できる必要があります。

select t1.region,
  t1.location,
  t1.customer,
  t1.customerkey,
  t1.status,
  case when t2.status is not null then 'Yes' else 'No' end VIPStatus
from yourtable t1
left join yourtable t2
  on t1.CustomerKey = t2.CustomerKey 
  and t2.Location = 'All States' 
  and t2.status = 'VIP Customer'
where t1.Location <> 'All States' 

デモで SQL Fiddle を参照してください

結果は次のとおりです。

| REGION |   LOCATION | CUSTOMER | CUSTOMERKEY |   STATUS | VIPSTATUS |
-----------------------------------------------------------------------
|  North |   New York |     John |         111 |   Active |        No |
|  North |   New York |     Mary |         112 |   Active |        No |
|  North |   Delaware |      Bob |         113 |     Idle |       Yes |
|  North | New Jersey |      Bob |         113 |   Active |       Yes |
|   West | California |      Bob |         113 | Inactive |       Yes |
|   West | Washington |     Greg |         114 | Inactive |       Yes |
|   West |       Utah |      Tim |         115 |   Active |        No |
于 2013-01-14T18:01:57.537 に答える