2017-04-06 114 views
1

請參見下表。SQL:對於列A的每個值,都以列C中的值爲基礎從列B中取值的新列

產品名稱| -------- -------標籤| --sub標籤

產品1 ------ | - 安全級別 - | - - 全

產品1 ------ | ------- -------色| --Orange

產品1 ------ | --- -regionç---- | --City甲

產品2 ------ | - 安全級別 - | --Limited

產品2 ------ | ----區域B ---- | - 城市F

在這個例子中,我想要一個新的列,將返回「全」三行產品1和「限制」兩行產品2.這是針對SQL Server的。到目前爲止,我已經得到了以下,但並不一定要帶A柱到它:

CASE WHEN標籤=「安全級別」再分標籤END AS SECURITYLEVEL

感謝您抽空看看。

+1

不知道你做了什麼。我是否正確地假設您需要每個獨特產品名稱的安全級別? –

回答

0
select [Product Name], 
     case when exists(select 1 from your_table as B where [Sub-tag] = 'Full' and B.[Product Name] = A.[Product Name]) then 'Full' 
      when exists(select 1 from your_table as B where [Sub-tag] = 'Limited' and B.[Product Name] = A.[Product Name]) then 'Limited' 
     end as [SecurityLevel] 
From your_table as A 
Group by [Product Name] 
3

使用條件與聚集窗口函數max()over()

select * 
    , SecurityLevel = max(case when Tag='Security Level' then SubTag end) 
     over (partition by ProductName) 
from t 

rextester演示:http://rextester.com/BZKM65131

回報:

+-------------+----------------+---------+---------------+ 
| ProductName |  Tag  | SubTag | SecurityLevel | 
+-------------+----------------+---------+---------------+ 
| Product 1 | Security Level | Full | Full   | 
| Product 1 | Color   | Orange | Full   | 
| Product 1 | Region C  | City A | Full   | 
| Product 2 | Security Level | Limited | Limited  | 
| Product 2 | Region B  | City F | Limited  | 
+-------------+----------------+---------+---------------+ 
+0

完美,謝謝Zim – MarkJ

+0

@MarkJ樂於幫忙! – SqlZim

相關問題