[英]Creating a pivot table in T-SQL?
我真的可以使用一些幫助來創建數據透視表。 我有一些行中的數據,而不是需要出現在列中,並置於其他記錄中的值旁邊。 數據目前采用以下格式:
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中非常感激。
您應該能夠多次加入表格以獲得所需的結果:
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'
結果是:
| 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 |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.