如何在T_SQl案例中做一个突破

时间:2014-03-10 16:29:32

标签: tsql

如下所示,只是一个大问题的一部分。 有没有更好的写作方式?

select @a=
    case @pcono
    when '00' then sum(ptdbal00)
    when '01' then sum(ptdbal00)+ sum(ptdbal01)
    when '02' then sum(ptdbal00)+ sum(ptdbal01)+sum(ptdbal02)
    ...



 end 

from accthist
where ...

2 个答案:

答案 0 :(得分:0)

“更好”是相当主观的,但不同,是的;

;WITH cte AS (
  SELECT ptdbal00 n, 0 m FROM test UNION ALL 
  SELECT ptdbal01 n, 1 m FROM test UNION ALL 
  SELECT ptdbal02 n, 2 m FROM test UNION ALL 
  SELECT ptdbal03 n, 3 m FROM test UNION ALL 
  SELECT ptdbal04 n, 4 m FROM test UNION ALL 
  SELECT ptdbal05 n, 5 m FROM test
)
SELECT @a=SUM(n) FROM cte WHERE m<=@pcono

An SQLfiddle to test with

说实话,看起来您可能需要查看规范化数据库。

答案 1 :(得分:0)

这个怎么样,我认为性能是一样的,但它更容易阅读和维护:

select @a=sum(ptdbal00) + 
    case when @pcono >= '01' then sum(ptdbal01) else 0 end+
    case when @pcono >= '02' then sum(ptdbal02) else 0 end+
    case when @pcono >= '03' then sum(ptdbal03) else 0 end+
    case when @pcono >= '04' then sum(ptdbal04) else 0 end+
    case when @pcono >= '05' then sum(ptdbal05) else 0 end+
    case when @pcono >= '06' then sum(ptdbal06) else 0 end+
    ...



 end 

from accthist
where ...