2017-10-10 89 views
1

我試圖使這個select語句到將採取「總和(PRSummaryMain.Revenue)」和更新領域的數據庫「的更新語句ClientCusttabfields.Cust12MonthRev 「更新SQL場與聲明的Where子句和與內部連接

我看到的一切嘗試失敗了呢?

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 >[email protected] and PRSummaryMain.period <[email protected] and ClientCustomTabFields.CustStrategicClient like 'y' 

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

你可以添加你嘗試過什麼樣的例子,怎麼會失敗? –

+0

的可能的複製[如何從選擇更新在SQL Server?(https://stackoverflow.com/questions/2334712/how-do-i-update-from-a-select-in-sql-server) –

回答

0

你可以試試下面的查詢:

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 >[email protected] 
    and PRSummaryMain.period <[email protected] 
    and c1.CustStrategicClient like 'y' 
group by cl.Client, CL.clientid, cl.Name