2016-09-16 136 views
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 
+0

你不應該包括Veh_table.Amount在GROUP BY而是概括 – StanislavL

+1

第一個查詢組由包含VV_table.Furit,而第二doen't。因此你得到不同的總和值。聚合操作並不相同。 – istovatis

+0

@StanislavL當我從組中刪除數量,然後顯示多個結果和錯誤發生列'Veh_table.Amount'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。 – user6628729

回答

0

不能刪除VV_table從查詢而不如果有在現場福瑞特在此表(VV_table.Furit =「」)的空值變化的結果。條件

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; 

它不是侑的查詢答案,但提高閱讀查詢,讓你擺脫子查詢。