按不同的分组划分两行

时间:2014-04-08 15:39:08

标签: sql sql-server

我正在尝试运行一个计算百分比的更新语句。我想要做的是基本上获得具有多源代码的单位数量' y'并将它们除以没有多源代码的单位总数' y。我可以将它归结为单元和多源代码的分组,但是从那里进行实际计算时遇到了麻烦。下面是代码。

update erosiondata2
set Erosion1 = 

(select     
    sum(Units) TotalUnits,
    MultiSourceCode
from 
    wkdata2 w join mddb m on w.ndc11 = m.ndc join ErosionData2 e on e.genprodident = m.genprodident
where 
    e.GenProdIdent = '44505080000310' and m.RepckgCode <> 'x' and w.RecordDate = e.GenericLaunchDate
group by 
    MultiSourceCode)

我也可以像下面那样运行它,但它需要永远。

update erosiondata2
set genericlaunchdate = 

select  
    (select sum(Units) from wkdata2 w join mddb m on w.ndc11 = m.ndc join ErosionData2 e on e.genprodident = m.genprodident
    where erosiondata2.genprodident = m.GenProdIdent and m.RepckgCode <> 'x' and w.RecordDate = e.GenericLaunchDate and MultiSourceCode = 'Y') / sum(t.units)

FROM
(select SUM(units) Units from wkdata2 w join mddb m on w.ndc11 = m.ndc join ErosionData2 e on e.genprodident = m.genprodident
    where erosiondata2.genprodident = m.GenProdIdent and m.RepckgCode <> 'x' and w.RecordDate = e.GenericLaunchDate and MultiSourceCode <> 'y') t

这是有效的代码。但是,它需要一段时间才能运行。

update erosiondata2
set Erosion1 = 

(Select 
    SUM(Case When MultiSourceCode = 'Y' Then TotalUnits Else 0 End) / SUM(TotalUnits)
FROM
    (select     
        MultiSourceCode,
        sum(Units) TotalUnits

    from 
        wkdata2 w join mddb m on w.ndc11 = m.ndc join ErosionData2 e on e.genprodident = m.genprodident
    where 
        erosiondata2.genprodident = m.GenProdIdent and m.RepckgCode <> 'x' and w.RecordDate = e.GenericLaunchDate
    group by 
        MultiSourceCode)t)

2 个答案:

答案 0 :(得分:0)

WITH  CTE as 
(SELECT sum(Units) TotalUnits, MultiSourceCode
FROM wkdata2 w 
INNER JOIN  mddb m 
  on w.ndc11 = m.ndc 
INNER JOIN ErosionData2 e 
  on e.genprodident = m.genprodident
where e.GenProdIdent = '44505080000310' 
  and m.RepckgCode <> 'x' 
  and w.RecordDate = e.GenericLaunchDate
group by MultiSourceCode)

SELECT (Select cte.totalUnits from CTE where MultiSourceCode = 'Y') / 
    (Select cte.totalUnits from CTE where coalesce(MultiSourceCode,'N') <> 'Y' )

我认为这应该给你正确的数学。从这里你可以找出更新。

答案 1 :(得分:0)

With MultiSourceCodeUnits as (
    select     
        MultiSourceCode,
        sum(Units) TotalUnits

    from 
        wkdata2 w join mddb m on w.ndc11 = m.ndc join ErosionData2 e on e.genprodident = m.genprodident
    where 
        e.GenProdIdent = '44505080000310' and m.RepckgCode <> 'x' and w.RecordDate = e.GenericLaunchDate
    group by 
        MultiSourceCode
)
Select MultiSourceCode,
       TotalUnits / SUM(Case When MultiSourceCode <> 'Y' Then TotalUnits Else 0 End)
FROM MultiSourceCodeUnits