0
當我嘗試此查詢金額導致SQL查詢
Select S.Name,S.No,
SUM(Case when s.Furit =’Mango’ then total else 0 end) as Mango,
SUM(Case when s.Furit =’Apple’ then total else 0 end) as Apple,
SUM(total) total,
Sum(convert(int,Am)) Amount, MAX(S.Value) Value
from (
Select
Veh_table.Name, Veh_table.No, VV_table.Furit, count(VV_table.Furit) as total, Veh_table. Amount as Am, Veh_table. Value
from VV_table
inner join Veh_table on VV_table.MID=Veh_table.ID
inner join Re_table on Veh_table.RID=Re_table.RID
WHERE
Re_table.StartDate>= '2016-08-01 00:00:00' and
Re_table.EndDate<='2016-08-31 23:59:59' and
Re_table.Region= 'UK'
and Veh_table.No= '431'
AND Furit <> ''
Group By Veh_table.Name, Veh_table.RegNo, VV_table.Furit,Veh_table.Amount,Veh_table.Value) S
GROUP BY
s.No,s.Name
這個節目的結果是這樣
Name No Mango Apple total Amount Value
John 431 9 2 11 964 98
當我從上面去除水果和嘗試這個
Select S.Name,S.No
SUM(total) total,
Sum(convert(int,Am)) Amount, MAX(S.Value) Value
from (
Select
Veh_table.Name, Veh_table.No,count(VV_table.Furit) as total, Veh_table.Amount as Am, Veh_table.Value
from VV_table
inner join Veh_table on VV_table.MID=Veh_table.ID
inner join Re_table on Veh_table.RID=Re_table.RID
WHERE
Re_table.StartDate>= '2016-08-01 00:00:00' and
Re_table.EndDate<='2016-08-31 23:59:59' and
Re_table.Region= 'UK'
and Veh_table.No= '431'
AND Furit <> ''
Group By Veh_table.Name, Veh_table.RegNo, Veh_table.Amount,Veh_table.Value) S
GROUP BY
s.No,s.Name
Name RegNo total Amount Value
John 431 11 243 98
現在我芒果和蘋果在數據中也要正確的數量是243。當我從選擇刪除VV_table.Furit則達243顯示這是正確的,而當我添加VV_table.Furit則達964顯示這是不對的 我想造成這樣的
Name No Mango Apple total Amount Value
John 431 9 2 11 243 98
你不應該包括Veh_table.Amount在GROUP BY而是概括 – StanislavL
第一個查詢組由包含VV_table.Furit,而第二doen't。因此你得到不同的總和值。聚合操作並不相同。 – istovatis
@StanislavL當我從組中刪除數量,然後顯示多個結果和錯誤發生列'Veh_table.Amount'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。 – user6628729