因此,我希望每个客户在两年内都有发票的总发票。所以我有
SELECT Sum((tbl_invoice_details.quantity
- ifnull(tbl_invoice_details.quantity_returned, 0)
) * tbl_invoice_details.price) AS dollarsSold,
tbl_customers.NAME,
cust_ID AS customer_id,
YEAR (tbl_invoice.invoice_date) AS invoiceYear
FROM `tbl_invoice_details`
INNER JOIN `tbl_invoice`
ON `tbl_invoice_details`.`invoice_ID` = `tbl_invoice`.`invoice_ID`
INNER JOIN `tbl_customers`
ON `tbl_customers`.`customer_ID` = `tbl_invoice`.`cust_ID`
WHERE MONTH (`invoice_date`) = '2'
AND (YEAR (`invoice_date`) = '2017'
OR
YEAR (`invoice_date`) = '2016')
AND EXISTS (SELECT *
FROM tbl_invoice
WHERE cust_ID = customer_id
AND MONTH (`invoice_date`) = '2'
AND YEAR (`invoice_date`) = '2016')
GROUP BY MONTH (tbl_invoice.invoice_date),
invoiceYear,
`tbl_customers`.`name`,
customer_id
ORDER BY name
那么如何将其限制在2016年和2017年2月发票的客户。我尝试使用EXISTS
,但这只是成功的一半。
答案 0 :(得分:1)
确保两张发票存在的最佳方法是使用EXISTS两次,一次使用2016年,另一次使用2017年。
SELECT Sum((tbl_invoice_details.quantity
- ifnull(tbl_invoice_details.quantity_returned, 0)
) * tbl_invoice_details.price) AS dollarsSold,
tbl_customers.NAME,
cust_ID AS customer_id,
YEAR (tbl_invoice.invoice_date) AS invoiceYear
FROM `tbl_invoice_details`
INNER JOIN `tbl_invoice`
ON `tbl_invoice_details`.`invoice_ID` = `tbl_invoice`.`invoice_ID`
INNER JOIN `tbl_customers`
ON `tbl_customers`.`customer_ID` = `tbl_invoice`.`cust_ID`
WHERE MONTH (`invoice_date`) = '2'
AND YEAR (`invoice_date`) IN ('2016', '2017')
AND EXISTS (SELECT 1
FROM tbl_invoice
WHERE cust_ID = customer_id
AND MONTH (`invoice_date`) = '2'
AND YEAR (`invoice_date`) = '2016')
AND EXISTS (SELECT 1
FROM tbl_invoice
WHERE cust_ID = customer_id
AND MONTH (`invoice_date`) = '2'
AND YEAR (`invoice_date`) = '2017')
GROUP BY MONTH (tbl_invoice.invoice_date),
invoiceYear,
`tbl_customers`.`name`,
customer_id
ORDER BY name;