在T-SQL中创建数据透视表?

时间:2013-01-14 17:53:32

标签: sql tsql pivot pivot-table

我真的可以使用一些帮助来创建数据透视表。我有一些行中的数据,而不是需要出现在列中,并置于其他记录中的值旁边。 数据目前采用以下格式:

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客户”状态的记录,则在“区域”和“所有州”的相应“位置”值的组合下,将显示“是”的“VIP状态”或者在该给定区域下该客户的任何记录下的“否”(无论位置状态如何)。有一个简单的解决方案吗?在T-SQL中重新排列这些数据的任何帮助都将非常感激。

1 个答案:

答案 0 :(得分: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 with Demo

结果是:

| 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 |