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

问题在于“状态”列,它可以有一组值(非活动/活动/空闲)和另一组值(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 回答