SQL:试图理解IF / ELSE

时间:2015-07-22 14:35:40

标签: sql sql-server

SELECT CASE r.SourceId
                        WHEN '1' THEN 'ITUNES' 
                        WHEN '2' THEN 'SFR'
                        WHEN '3' THEN 'ORANGE' 
                        ELSE 'Others'
                        END as source 
, CAST(SUM (r.SalesVolume) AS DECIMAL(14, 4) ) AS Volume
, CAST(SUM (r.SalesVolume * r.CustomerPrice) AS DECIMAL(14, 4) ) AS Value 
from Rawdata r 
    INNER JOIN Product p
        ON p.ProductId = r.ProductId
    INNER JOIN Calendar c 
        ON r.DayId = c.DayId
        WHERE c.WeekId BETWEEN (20145227) AND (20155230)
        AND p.ContentFlavor IN ('SD', 'HD')
        AND p.VODEST IN ('VOD','EST')
        AND p.Distributor IN ('M6SND')
        GROUP BY  CASE r.SourceId
            WHEN '1' THEN 'ITUNES' 
            WHEN '2' THEN 'SFR'
            WHEN '3' THEN 'ORANGE' 
            ELSE 'Others'
            END

上述查询的结果是:

source  Volume      Value
ITUNES  48316.0000  506067.2600

此结果完全正常,因为我的源表RawData不包含SourceId 23的任何值。 但我基本上想要的结果是:

source  Volume      Value
ITUNES  48316.0000  506067.2600
SFR     0           0
ORANGE  0           0
Others  0           0

如果没有与任何列参数对应的值,那么我需要它为0 我假设这可以使用IF / ELSE完成,但不确定如何?

2 个答案:

答案 0 :(得分:1)

在CTE的帮助下,这是一种方法。 (如果需要,用更动态的东西替换第一个查询)

with myChoices (choices)
as (
    select
        choices
    from (
        values
        ('ITUNES'),
        ('SFR'),
        ('ORANGE'),
        ('Others')
    ) [ ] (choices)
),
myQuery ([source],[Volume],[Value])
as (
    SELECT CASE r.SourceId
                        WHEN '1' THEN 'ITUNES' 
                        WHEN '2' THEN 'SFR'
                        WHEN '3' THEN 'ORANGE' 
                        ELSE 'Others'
                        END as source 
    , CAST(SUM (r.SalesVolume) AS DECIMAL(14, 4) ) AS Volume
    , CAST(SUM (r.SalesVolume * r.CustomerPrice) AS DECIMAL(14, 4) ) AS Value 
    from Rawdata r 
    INNER JOIN Product p
        ON p.ProductId = r.ProductId
    INNER JOIN Calendar c 
        ON r.DayId = c.DayId
        WHERE c.WeekId BETWEEN (20145227) AND (20155230)
        AND p.ContentFlavor IN ('SD', 'HD')
        AND p.VODEST IN ('VOD','EST')
        AND p.Distributor IN ('M6SND')
        GROUP BY  CASE r.SourceId
            WHEN '1' THEN 'ITUNES' 
            WHEN '2' THEN 'SFR'
            WHEN '3' THEN 'ORANGE' 
            ELSE 'Others'
            END
)
select
    c.choices,
    ISNULL(q.Volume,0)Volume,
    ISNULL(q.Value,0)Value
from myChoices c 
left join myQuery q on
    c.choices = q.[source]

答案 1 :(得分:0)

  1. 创建一个名为" Product_Inline_View"的内联视图,就像 (选择1作为SourceId,' ITUNES'作为source_name 联合所有 选择2作为SourceId,' SFR'作为source_name 联合所有 选择3作为SourceId,' ORANGE'作为source_name )
  2. 使用您拥有的查询加入Product_Inline_view,但不使用CASE。
  3. 然后按小组进行。