这是我的第一个问题,我还在学习Mysql,所以我遇到的问题是将两个查询组合在一起
第一次查询:
SELECT
stocks.Stock_Trans_No
stocks.Stock_Date_Time,
stocks.Stock_Trans_Type,
stocks.Stock_Trans_Ref_No,
stocks.Stock_Trans_Item_Code,
stocks.Stock_Trans_Qty,
stocks.Item_Description
FROM stocks
WHERE
DATE_FORMAT( stocks.Stock_Date_Time, '%Y%m%d') BETWEEN DATE_FORMAT('2015-09-01', '%Y%m%d') AND DATE_FORMAT('2015-11-01', '%Y%m%d') GROUP BY stocks.`Stock_Trans_Item_Code`
第二次查询:
SELECT
SUM( stocks.Stock_Trans_Qty)
FROM stocks
WHERE
DATE_FORMAT( stocks.Stock_Date_Time, '%Y%m%d') > '2015-09-01'
GROUP BY stocks.`Stock_Trans_Item_Code`
我如何将这些结合在一起。我还在学习,请尽可能简单!谢谢
答案 0 :(得分:2)
试试这个..
SELECT
SUM( IF(DATE_FORMAT( stocks.Stock_Date_Time, '%Y%m%d') > '2015-09-01',stocks.Stock_Trans_Qty,0)) AS Stock_Trans_Qty_Sum
stocks.Stock_Trans_No
stocks.Stock_Date_Time,
stocks.Stock_Trans_Type,
stocks.Stock_Trans_Ref_No,
stocks.Stock_Trans_Item_Code,
stocks.Stock_Trans_Qty,
stocks.Item_Description
FROM stocks
WHERE
DATE_FORMAT( stocks.Stock_Date_Time, '%Y%m%d') BETWEEN DATE_FORMAT('2015-09-01', '%Y%m%d') AND DATE_FORMAT('2015-11-01', '%Y%m%d') GROUP BY stocks.`Stock_Trans_Item_Code`
答案 1 :(得分:0)
试试这个
SELECT s1.*,
(SELECT SUM(s2.Stock_Trans_Qty)
FROM stocks as s2
WHERE
s2.Stock_Trans_Item_Code = s1.Stock_Trans_Item_Code AND
DATE_FORMAT(s2.Stock_Date_Time, '%Y%m%d') > '2015-09-01'
) Total
FROM stocks as s1
WHERE
DATE_FORMAT(s1.Stock_Date_Time, '%Y%m%d') BETWEEN DATE_FORMAT('2015-09-01', '%Y%m%d') AND DATE_FORMAT('2016-11-01', '%Y%m%d')
GROUP BY s1.`Stock_Trans_Item_Code`