2016-07-13 216 views
1

我有一個表格「關係」,它存儲了費率和交易之間的關係。 它看起來像:如何根據SQL中的其他列值選擇布爾列?

DealId    RateId  IsPremium 
------------------------------------------------ 
    1     A   True 
    2     A   False   
    3     B   False 
    4     B   True 
    5     B   True 
    6     C   False 
    7     C   False 

DealId是唯一的,一個RateId可以映射到許多不同的DealId。

現在,Buesiness球隊要求我提供一個關於此表中報告,但IsPremium值將被更改爲如果該表中的相同RateId已經值。

這意味着,基於請求,我的新報告將是:

DealId    RateId  IsPremium 
------------------------------------------------ 
    1     A   True 
    2     A   True   
    3     B   True 
    4     B   True 
    5     B   True 
    6     C   False 
    7     C   False 

由於RateId C沒有在原來的表價值,我將繼續呈現假值了。

我想在我的SQL腳本中使用 「GROUP BY RateId」,但不能與IsPremium值處理...

回答

3

一種方法是

SELECT DealId, 
     RateId, 
     MAX(IsPremium) OVER (PARTITION BY RateId) AS IsPremium 
FROM YourTable 

Online demo

(我假設你的列是varchar,字符串爲「true」和「false」,因爲SQL Server沒有布爾列。類似的將會對bit和1/0有效)

SELECT DealId, 
     RateId, 
     CAST(MAX(CAST(IsPremium AS INT)) OVER (PARTITION BY RateId) AS BIT) AS IsPremium 
FROM YourTable 
1
Solution of Martin work on SGBD with OLAP function (good idea Martin ;) ) 


Solution 2: 
select DealId, RateId, 
case when ispremium =1 then 1 
when (select count(*) from relation f2 where f1.dealid<>f2.dealid and f2.rateid=f1.rateid and ispremium=1)>0 then 1 
else 0 end ispremium 
from relation f1 
1

解決方案3:

with maxi as (
select RateId, 
max(cast(ispremium as integer)) ispremium 
from test0713 f1 
group by RateId 
) 
select f1.dealid, f2.* 
from test0713 f1 inner join maxi f2 on f1.RateId=f2.RateId