如何根据SQL中的其他列值选择布尔列?

时间:2016-07-13 20:19:14

标签: sql-server

我有一个表“关系”,它存储了Rate和Deal之间的关系。 它看起来像:

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团队要求我提供有关此表的报告,但 True 值将更改为 True 如果相同的RateId在此表中已有 True 值。

这意味着,根据请求,我的新报告将是:

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在原始表中没有 True 值,因此我将继续以False值显示它。

我尝试在我的SQL脚本中使用“Group BY RateId”,但无法处理IsPremium中的值......

3 个答案:

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

答案 2 :(得分:1)

解决方案3:

realm.objectForPrimaryKey(Note.self, key: "C5AD8E58-912E-4C32-B67D-748B0621266A")
相关问题