SQL检查范围中的多个字段是否> 0

时间:2015-07-02 09:51:12

标签: sql sql-server

在SQL-Server中,我在表中有4个字段,我想检查是否有多个是> 0,如果是这样,则将新字段的值设置为1.例如,

RowID Football Cricket Tennis Athletics
1     0        2       0      1
2     1        0       0      0

第一行评估为1,第二行不评估。

如何构建案例陈述来评估多个字段?

由于

3 个答案:

答案 0 :(得分:4)

尝试以下,

Select RowId, Case when NewField > 1 then 1 else 0 end as 'Status' from 
(
    Select *,
        case when Football > 0 then 1 else 0 end +
        case when Cricket > 0 then 1 else 0 end +
        case when Tennis > 0 then 1 else 0 end +
        case when Athletics > 0 then 1 else 0 end as 'NewField'
    from TableName
)

答案 1 :(得分:1)

纯粹在可能的概念中,所以我不是说它更好或更糟,你也可以先取消结果以规范化数据。

例如,这会显示体育运动及其数量在彼此之下:

select RowID, Sport, SportCount
from YourTableName
unpivot
( SportCount for Sport in (Football, Cricket, Tennis, Athletics )) up

从那里获得每个身份的运动数量相对简单:

select rowid, SUM(case when SportCount > 0 then 1 else 0 end) NumberOfSports from(
select RowID,  SportCount
from YourTableName
unpivot
( SportCount for Sport in (Football, Cricket, Tennis, Athletics )) up
) q group by rowid

或者在体育赛事数量的更新查询中使用> 2(当然可能采用其他方法)

update YourTableName set SomeField = 1 where RowID in
(
select rowid from(
select RowID,  SportCount
from YourTableName
unpivot
( SportCount for Sport in (Football, Cricket, Tennis, Athletics )) up
) q group by rowid
having SUM(case when SportCount > 0 then 1 else 0 end) > 1)

通过解开麻烦的优势在于,标准的逻辑在一个地方。如果将来您想要查看具有多个运动且计数超过2的所有行,则只有一个位置可以更新。性能方面我可能会坚持使用case footb + case cricket + ..方法。

答案 2 :(得分:0)

请检查这是否有帮助

INSERT INTO dbo.tests
    ( RowID ,
      Football ,
      Cricket ,
      Tennis ,
      Athletics
    )VALUES  ( 1 , -- RowID - int
      0 , -- Football - int
      2 , -- Cricket - int
      0 , -- Tennis - int
      1  -- Athletics - int
    ),
    ( 1 , -- RowID - int
      0 , -- Football - int
      2 , -- Cricket - int
      0 , -- Tennis - int
      1  -- Athletics - int
    )
SELECT COUNT(*) FROM(select *from dbo.tests
unpivot (value for name in (Football,Cricket,Tennis,Athletics)) up
pivot (max(value) for RowID in ([1],[2])) p) AS t WHERE [1]>0

由于