2017-09-26 186 views
0

所以,我有兩個數據,他們我以前不具有任何關係如何選擇基於另一個選擇值同月值

第一表

tglAmbil Satuan Harga 
11-08-2017 1  10000 
11-08-2017 2  10000 
15-08-2017 2  10000 
01-09-2017 2  10000 

二表

tglAmbil Satuan Harga 
21-08-2017 1  10000 

我試着讓我的SELECT結果如下所示:

Month(tglAmbil) date_format(tglAmbil,"$m") Harga 
8     Agustus      60000 
9     September     20000 
使用10

此查詢:

SELECT 

MONTH(`tglAmbil`), 

DATE_FORMAT(tglAmbil,"%M"), 

SUM(detaillpjunbudged.satuan * detaillpjunbudged.harga) + 
IFNULL(prokers.total,0) 

FROM `unbudged` LEFT JOIN lpjunbudged ON unbudged.kdUnbudgeding = 
lpjunbudged.kdUnbudgeding 

LEFT JOIN detaillpjunbudged ON lpjunbudged.kdLpjUnbudged = 
detaillpjunbudged.kdLpjUnbudged, 

(SELECT MONTH(`tglAmbil`) AS 
tgl,DATE_FORMAT(tglAmbil,"%M"),SUM(detaillpjproker.satuan * 
detaillpjproker.harga) AS total,`kdDetailProker` FROM `realisasiproker` LEFT 
JOIN lpjproker ON realisasiproker.kdRealisasiProker = 
lpjproker.kdRealisasiProker LEFT JOIN detaillpjproker ON lpjproker.kdLPJ = 
detaillpjproker.kdLPJ GROUP BY MONTH(tglAmbil)) AS prokers 

WHERE MONTH(`tglAmbil`) = prokers.tgl GROUP BY MONTH(`tglAmbil`) 

但我得到的結果:

Month(tglAmbil) date_format(tglAmbil,"$m") Harga 
8     Agustus      60000 

所以,什麼叫真正的原因是什麼?我對這個sytax問題感到困惑。謝謝

回答

0

考慮以下幾點:

DROP TABLE IF EXISTS table1; 

CREATE TABLE table1 
(purchase_date DATE NOT NULL 
,quantity INT NOT NULL 
,price INT NOT NULL 
); 

INSERT INTO table1 VALUES 
('2017-08-11',1,10000), 
('2017-08-11',2,10000), 
('2017-08-15',2,10000), 
('2017-09-01',2,10000); 

DROP TABLE IF EXISTS table2; 

CREATE TABLE table2 
(purchase_date DATE NOT NULL 
,quantity INT NOT NULL 
,price INT NOT NULL 
); 

INSERT INTO table2 VALUES 
('2017-08-21',1,10000); 


SELECT DATE_FORMAT(purchase_date,'%Y-%m') yearmonth 
    , SUM(quantity*price) total 
    FROM 
    (
    SELECT * FROM table1 
     UNION 
    SELECT * FROM table2 
    ) x 
GROUP 
    BY yearmonth; 
+-----------+-------+ 
| yearmonth | total | 
+-----------+-------+ 
| 2017-08 | 60000 | 
| 2017-09 | 20000 | 
+-----------+-------+ 
+0

謝謝你,它的工作時,我嘗試在我自己的表。但是當我檢查SUM值與實際值不同的值時(例如:實際值是23305000,但它只顯示值23255000)。 –

+0

啊,對不起。沒關係我最後的評論問題。我已經找出了問題。 –

相關問題