【问题标题】:select case with "over partition by"选择带有“over partition by”的案例
【发布时间】:2015-12-10 03:27:21
【问题描述】:

什么是正确的语法,或者是否可以在 select 中使用 case 并在其中分区? (使用 sql server 2012)

a = unique id
b = a string'xf%'
c = values
d = values 
e = values



select 
    case 
    when b like 'xf%' then
    (sum(c*e)/100*3423 over (partition by a))end as sumProduct
from #myTable

这是我需要解决的问题,这是我遇到的问题的一部分 以前sumProduct in sql

编辑:根据要求添加一些示例数据和预期结果 创建表#testing(b varchar (20), a date, c int, e int)

     b           a           c         e       sumProduct (expected)
    xf1m    2015.03.02       1         3       (1*3 + 2*5 + 4*2 +3*6)*100/3423
    xf3m    2015.03.02       2         5       (1*3 + 2*5 + 4*2 +3*6)/100*3423
    xf5y    2015.03.02       4         2       (1*3 + 2*5 + 4*2 +3*6)/100*3423
    xf10y   2015.03.02       3         6       (1*3 + 2*5 + 4*2 +3*6)/100*3423
    adfe    2015.03.02       2         5    ---this is skipped because is not xf%
    xf1m    2013.02.01       7         2        (7*2 + 1*8 + 10*1)/100*3423
    xf15y   2013.02.01       1         8        (7*2 + 1*8 + 10*1)/100*3423
    xf20y   2013.02.01       10        1        (7*2 + 1*8 + 10*1)/100*3423

我发现问题是这样的:即使不符合标准,也会被累加。在我的小提琴中,您可以看到 sumProduct 的结果是 49 而不是 39,因为正在添加来自 adfe 的 2*5。我能做些什么呢?

create table #testing (b varchar (20), a date, c int, e int)

insert into #testing (b,a,c,e)
values
('xf1m','2015-03-02','1','3'),
('xf3m','2015-03-02','2','5'),
('xf5y','2015-03-02','4','2'),
('xf10y','2015-03-02','3','6'),
('adfe','2015-03-02','2','5'),
('xf1m','2013-02-01','7','2'),
('xf15y','2013-02-01','1','8'),
('xf20y','2013-02-01','10','1')

编辑:找到解决方案,将其写为下面的答案

【问题讨论】:

  • 我可以用另一种方式重新表述问题吗?或者我做错了什么(关于否决票)。还是这个网站的新手,任何建议都会有所帮助。谢谢

标签: sql sql-server tsql sql-server-2012 window-functions


【解决方案1】:

您不能在Aggregate() OVER (PARTITION clause) 表达式内放置任意表达式 - 所以将额外的计算移到外面:

select 
    case 
    when b like 'xf%' then
    (sum(c*e) over (partition by a))/100*3423 end as sumProduct
from #myTable

【讨论】:

  • 这正是我想要的。谢谢,无法弄清楚这部分,如此接近但到目前为止
  • 如果 a 是日期而不是 ID 怎么办。那么我可以假设我的代码会为每个日期生成 (ce)/100*3423 的总和吗?问题是,我的代码有效,但我得到的结果甚至与我想要的结果相差甚远。我想要的是:对于每个日期,将 ce 的值相乘并将其与下一个 c*e 的值相加,下一个项目的格式为“xf%”。我的问题是:我的逻辑仍然适用于我想要的吗?
  • @viorelmunteanu - 如果您需要更详细的帮助,可以编辑您的问题并添加一些 sample 数据和 expected 结果。有时,仅从叙述中很难理解某人试图做什么。
【解决方案2】:

找到了我在编辑中提出的问题的解决方案:

 select
 b,
 a,
 c,
 e,
case 
when b like 'xf%' then -- 
(sum(c * e) over (partition by a ))/*/3*10*/ end as sumProduct
into #testing2
from #testing
where (b like 'xf%')

select t1.b, t1.a,t1.c,t1.e,t2.sumProduct 
from #testing t1
left join #testing2 t2 on t1.a = t2.a and t2.b = t1.b
order by t1.a, t1.b

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多