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