SQL查询中的数量结果

时间:2016-09-16 07:15:08

标签: sql sql-server sum max

当我尝试此查询时

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

现在我想要Mango和Apple的数据也是正确的数量是243。当我从select中删除VV_table.Furit然后显示金额243是正确的而当我添加VV_table.Furit然后显示金额964是错误的 我想要这样的结果

Name    No  Mango   Apple   total   Amount  Value
John    431     9   2        11     243      98

1 个答案:

答案 0 :(得分:0)

如果此表格中的字段 Furit 中存在空值(VV_table.Furit =''),则无法从查询中删除 VV_table 而不更改结果。条件

AND Furit <> ''

更正没有空值的结果。

此外,您应该使用带语法的方法,如下所示:

WITH pre AS (
    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
)
SELECT pre.Name,pre.No,
  SUM(CASE WHEN pre.Furit =’Mango’ THEN total ELSE 0 AND) AS Mango,
  SUM(CASE WHEN pre.Furit =’Apple’ THEN total ELSE 0 AND) AS Apple,
  SUM(total) AS total,
  Sum(convert(int,Am)) AS Amount,
  MAX(pre.Value) AS Value
FROM pre 
GROUP BY pre.No,pre.Name;

它不是对yor查询的回答,但改进了阅读查询并允许你摆脱子查询。