基于3列总和返回数据的存储过程

时间:2015-09-16 21:36:00

标签: sql sql-server stored-procedures

我有一个存储过程如下:

SELECT   DiscountId
        ,CompanyId
        ,Discount1
        ,Discount2
        ,Discount3  
        ,(Discount1+Discount2+Discount3) as Total
FROM PriceDiscount

这可以返回一行或多行。

我还需要检查Discount1,Discount2和Discount3的总和。如果任何行的总和大于0,我想设置一列isDiscounted = true并将其返回。

请帮助我 - 我怎样才能实现这一目标?

我不想在代码中检查这个或为此创建另一个存储过程。因此,希望返回此存储过程的结果。

1 个答案:

答案 0 :(得分:2)

您可以使用case来计算/设置isDiscounted列。

with x as (
SELECT DiscountId
    ,CompanyId
    ,Discount1
    ,Discount2
    ,Discount3  
    ,case when (Discount1+Discount2+Discount3) > 0 then 'True'
     else 'False' end  as isDiscounted
FROM PriceDiscount)
, y as (select case when isDiscounted = 'True' then count(*) end as true_count,
               case when isDiscounted = 'False' then count(*) end as false_count
        from x group by isDiscounted)
select case when true_count > 0 then 'True'
            when falsecount > 0 and truecount = 0 then 'False' end
       as final_status
from y

编辑:

with x as (
SELECT DiscountId
    ,CompanyId
    ,Discount1
    ,Discount2
    ,Discount3  
    ,case when (Discount1+Discount2+Discount3) > 0 then 'True'
     else 'False' end  as isDiscounted
FROM PriceDiscount)
, y as (select sum(case when isDiscounted = 'True' then 1 else 0 end) as true_count,
               sum(case when isDiscounted = 'False' then 1 else 0 end) as false_count 
        from x)
select case when true_count > 0 then 'True'
            when false_count > 0 and true_count = 0 then 'False' end
       as final_status
from y