我正在处理汇总查询,该汇总查询将汇总交易总数,提取最近的交易日期,并提取最近的交易数量。我到目前为止所做的是:
SELECT
A.bill_cust_code,
A.product_code,
A.pack_code,
C.name,
MAX(A.invoice_date) AS last_purchase_date,
SUM(IF(A.invoice_date>DATE_FORMAT(NOW(), '%Y'),A.total_sales,0)) AS ytd_sales,
SUM(IF(A.invoice_date<DATE_FORMAT(NOW(), '%Y') AND A.invoice_date>DATE_FORMAT(NOW() - INTERVAL 1 YEAR, '%Y'),A.total_sales,0)) AS last_year_sales,
A.source
FROM
sales AS A
INNER JOIN
prodware AS B ON (B.product_code = A.product_code AND B.pack_code = A.pack_code AND B.warehouse_code = A.warehouse_code)
INNER JOIN
product AS C ON A.product_code=C.product_code
WHERE
B.type='Y'
GROUP BY
A.bill_cust_code,A.product_code,A.source
sales
表有数量列。如何提取与sales
对应的quantity
。MAX(A.invoice_date)
?
示例输出
+----------------+--------------+-----------+-------------------------------+--------------------+------------+-----------------+-----------+
| bill_cust_code | product_code | pack_code | name | last_purchase_date | ytd_sales | last_year_sales | source |
+----------------+--------------+-----------+-------------------------------+--------------------+------------+-----------------+-----------+
| 6 | DF2CARD | 110 | ULTRA LOW SULFUR DIESEL 2 C/L | 2012-01-31 | 1022213.71 | 13663316.61 | Cardlock |
| 6 | DF2CARD | 104 | ULTRA LOW SULFUR DIESEL 2 C/L | 2010-12-06 | 0.00 | 0.00 | Wholesale |
| 6 | DFGRCARD | 101 | GREEN DIESEL FUEL CARDLOCK | 2006-08-31 | 0.00 | 0.00 | Cardlock |
| 6 | DFGRPP | LOC | GREEN DIESEL FUEL PAC PRIDE | 2008-04-15 | 0.00 | 0.00 | Cardlock |
| 6 | DFRDCARD | 108 | ULTRA LOW DYED DIESEL 2 C/L | 2012-01-31 | 12678.35 | 136566.81 | Cardlock |
+----------------+--------------+-----------+-------------------------------+--------------------+------------+-----------------+-----------+
我想要另一列last_purchase_quantity
,这是MAX(A.invoice_date)
返回的记录中的数量。
答案 0 :(得分:0)
您可以将上述内容作为子查询,然后在外部查询中选择其他信息。 我没有测试我输入的内容,因为我没有这个结构所以请在输入时修正任何错误。
SELECT sub_tab.bill_cust_code,
sub_tab.product_code,
sub_tab.pack_code,
sub_tab.name,
sub_tab.last_purchase_date,
(select sales.quantity
from sales
where sales.invoice_date=sub_tab.last_purchase_date) as quantity,
sub_tab.ytd_sales,
sub_tab.last_year_sales,
sub_tab.source
RFOM (
SELECT
A.bill_cust_code,
A.product_code,
A.pack_code,
C.name,
MAX(A.invoice_date) AS last_purchase_date,
SUM(IF(A.invoice_date>DATE_FORMAT(NOW(), '%Y'),A.total_sales,0)) AS ytd_sales,
SUM(IF(A.invoice_date<DATE_FORMAT(NOW(), '%Y') AND A.invoice_date>DATE_FORMAT(NOW() - INTERVAL 1 YEAR, '%Y'),A.total_sales,0)) AS last_year_sales,
A.source
FROM
sales AS A
INNER JOIN
prodware AS B ON (B.product_code = A.product_code AND B.pack_code = A.pack_code AND B.warehouse_code = A.warehouse_code)
INNER JOIN
product AS C ON A.product_code=C.product_code
WHERE
B.type='Y'
GROUP BY
A.bill_cust_code,A.product_code,A.source
) sub_tab