2017-01-20 53 views
0

我正在使用SQL Server 2008 R2。我使用以下查詢查看包中所有產品的價格時間總和。通過從SQL Server 2008 R2中的另一個表中獲取總和來更新表條目

select 
    a.nid, a.packagename, 
    case 
     when sum(b.quantity * c.price) is null 
      then 0 
      else sum(b.quantity * c.price) 
    end 
from 
    tblpackage as a 
left join 
    tblpackage_service as b on a.nid = b.package_id 
left join 
    tblproduct as c on c.nid = b.service_id 
group by 
    a.nid, a.packagename 

返回以下結果

nid packagename  (No Column Name) 
--------------------------------------- 
6 Test Package 4 400.00 
3 Test Package 5  0.00 
5 Test Package 6 1350.00 
8 Test Package 7 350.00 
7 Test Package 8 400.00 
9 Test Package 9 400.00 
1 Test Package 1  0.00 
2 Test Package 2  0.00 
4 Test Package 3 3900.00 

現在我使用

update tblpackage 
set tblpackage.amount = case 
          when sum(b.quantity * c.price) is null 
           then 0 
           else sum(b.quantity * c.price) 
         end 
from tblpackage AS a 
left join tblpackage_service as b on a.nid = b.package_id 
left join tblproduct as c on c.nid = b.service_id 

更新相同的,我得到一個錯誤:

An aggregate may not appear in the set list of an UPDATE statement.

那麼,有什麼辦法使用更新來完成此操作查詢。

請幫忙。提前致謝。

回答

1

或許,這將更好地工作。

;WITH newtblpackage_service AS(
     SELECT package_id,SUM(quantity*price) as sum1 
     FROM tblpackage_service a left join tblproduct as c on c.nid = a.service_id 
     GROUP BY package_id 
) 

update tblpackage 
set tblpackage.amount = CASE WHEN sum1 IS NULL 
          THEN 0 
          ELSE sum1 
         END 
from tblpackage AS a 
left join newtblpackage_service as b on a.nid = b.package_id 

因爲tblpackage_service可以用來找到總和(所以它似乎)。

+0

它的工作原理,謝謝 – rexroxm

3

試試這個:

;WITH tblpackage_serviceCTE AS(
     SELECT package_id,SUM(quantity) as quantity 
     FROM tblpackage_service 
     GROUP BY package_id 
),tblproductCTE AS(
     SELECT nid,SUM(price) as price 
     FROM tblproduct 
     GROUP BY nid 
) 
update tblpackage 
set tblpackage.amount = CASE WHEN tblpackage_serviceCTE.quantity * tblproductCTE .price) IS NULL 
          THEN 0 
          ELSE tblpackage_serviceCTE.quantity * tblproductCTE .price 
         END 
from tblpackage AS a 
left join tblpackage_serviceCTE as b on a.nid = b.package_id 
left join tblproductCTE as c on c.nid = b.service_id 

注:以備份第一:對

+0

這麼想的工作,如價格不tblpackage_service – rexroxm

+0

@rexroxm的一部分'tblpackage_service'是錯字'tblproduct'應該有在第二CTC:0 –

+0

肯定,但通過創建tblproductCTE我將無法與加入吧tblpackageCTE,因爲它沒有service_id。 – rexroxm

相關問題