【问题标题】:Update SQL Field with Declared Where Clause Sum and inner join使用声明的 Where 子句总和和内部联接更新 SQL 字段
【发布时间】:2017-10-10 17:05:04
【问题描述】:

我正在尝试将此选择语句转换为更新语句,该语句将采用“Sum(PRSummaryMain.Revenue)”并更新数据库“ClientCusttabfields.Cust12MonthRev”中的字段

我看到的所有尝试都失败了?

declare @Now int, @12Month int, @lastMonth int, @day int
set @DAY = DATEPART(dd,getdate())
set @Now = LEFT(CONVERT(varchar, GetDate(),112),6)
set @12Month = iif(@day<20, @Now -102, @now-101)
set @lastmonth = iif(@day<20,@Now - 2,@now-1)

    select cl.Client, cl.ClientID, cl.Name, @12Month as 'Period-12months', @lastMonth as 'Period-lastmonth',
SUM(PRSummaryMain.Revenue) as '12monthrev'

From PRSummaryMain
inner join PR on (PRSummaryMain.WBS1 = PR.WBS1 and PRSummaryMain.WBS2=PR.WBS2 and PRSummaryMain.WBS3=PR.WBS3)

inner join CL on  (PR.ClientID = CL.ClientID) 
inner join ClientCustomTabFields on (cl.ClientID = ClientCustomTabFields.ClientID)

Where  PRSummaryMain.WBS1 not like 'P%'and PRSummaryMain.WBS1 not like '%i%' and PRSummaryMain.Period >=@12Month and PRSummaryMain.period <=@lastMonth and ClientCustomTabFields.CustStrategicClient like 'y'

group by cl.Client, CL.clientid, cl.Name
order by cl.Name 

【问题讨论】:

标签: sql-server join sum sql-update


【解决方案1】:

您可以尝试以下查询:

declare @Now int, @12Month int, @lastMonth int, @day int
set @DAY = DATEPART(dd,getdate())
set @Now = LEFT(CONVERT(varchar, GetDate(),112),6)
set @12Month = iif(@day<20, @Now -102, @now-101)
set @lastmonth = iif(@day<20,@Now - 2,@now-1)

select @Now , @12Month , @lastMonth , @day 

update c1
set Cust12MonthRev= SUM(PRSummaryMain.Revenue)
from
    ClientCustomTabFields c1 
inner join CL 
    on (cl.ClientID = c1.ClientID)
inner join PR 
    on  (PR.ClientID = CL.ClientID) 
inner join PRSummaryMain
    on (PRSummaryMain.WBS1 = PR.WBS1 and PRSummaryMain.WBS2=PR.WBS2 and PRSummaryMain.WBS3=PR.WBS3)
Where  
    PRSummaryMain.WBS1 not like 'P%'
    and PRSummaryMain.WBS1 not like '%i%' 
    and PRSummaryMain.Period >=@12Month 
    and PRSummaryMain.period <=@lastMonth 
    and c1.CustStrategicClient like 'y'
group by cl.Client, CL.clientid, cl.Name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-10
    • 2023-03-17
    • 2011-04-14
    • 2016-08-17
    • 2014-07-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多