2016-05-11 108 views
0

我正在處理正常的查詢,但它不適用於某些情況。理想情況下,它應該可以工作,但我不知道我錯在哪裏。 下面是示例中,有三個表等資本機和QC如何使用MYSQL編寫查詢

enter image description here

查詢:

select all_dates.value1 as `Date`, coalesce(`Outward1(B_Qty)`,`Outward2(B_Qty)`,`Outward3(B_Qty)`, '0') as `Outward` 
from 
(select distinct C_Date as value1 from capital where P2_Goods like '750%' and Monthname(C_Date)='April' 
union all 
select distinct M_Date from machine where J_Id like '%750' and Monthname(M_Date)='April' 
union all 
select distinct QC_Date from qc where QC_Name like '750%' and Monthname(QC_Date)='April' 
) as all_dates 
left join(select C_Date, sum(PR) AS `Outward1(B_Qty)` 
from capital where P2_Goods like '750%' and Monthname(C_Date)='April' group by C_Date) 
as f on f.C_Date = all_dates.value1 
left join(select M_Date, (sum(PR)+sum(C_Skip)) AS `Outward2(B_Qty)` 
from machine where J_Id like '%750' and Monthname(M_Date)='April' group by M_Date) 
as h on h.M_Date = all_dates.value1 
left join(select QC_Date, sum(PR) AS `Outward3(B_Qty)` 
from qc where QC_Name like '750%' and Monthname(QC_Date)='April' group by QC_Date) 
as k on k.QC_Date = all_dates.value1 group by all_dates.value1 

查詢的主要目的是,總計從每個表組PR和C_Skip柱的通過日期
現在,如果在兩個不同的表上有相同的日期,那麼它應該添加PR,但在這種情況下它不會添加。這就是問題所在。
請幫我。提前感謝。

回答

4

試試這個。

select date1,sum(outward) as outward from 
    (
    select c_date as date1,pr as outward from capital 
    union all 
    select m_date as date1,pr+c_skip as outward from machine 
    union all 
    select qc_date as date1,pr as outward from qc 
    ) t 
group by date1 
+0

它工作。複雜查詢轉化爲簡單查詢。做得好。非常感謝。需要學習很多。 – user007

+0

高興地幫助:) – Utsav