[BNM] MySQL SELECT statement Question
Karim Ahmed
bnm at karimahmed.com
Tue May 12 14:39:42 BST 2009
I've written SQL to produce a report in the following format but I can't
help thinking there must be a less verbose way of doing it. Any ideas
please? Thanks.
Customer Month 1 Sales Month 1 Profit Month 2 Sales Month 2 Profit
Name1 100 200 600 100
Name2 123 40 40 30
SELECT
Customer,
SUM(`Month 1 Sales`) AS `Month 1 Sales`,
SUM(`Month 1 Profit`) AS `Month 1 Profit`,
SUM(`Month 2 Sales`) AS `Month 2 Sales`,
SUM(`Month 2 Profit`) AS `Month 2 Profit`,
SUM(`Month 3 Sales`) AS `Month 3 Sales`,
SUM(`Month 3 Profit`) AS `Month 3 Profit`
FROM(
(
SELECT
cus_name AS Customer,
SUM(inl_qty * inl_unit_price) as `Month 1 Sales`,
SUM(inl_qty * inl_unit_price - inl_qty * inl_cost_price) AS `Month 1
Profit`,
0 as `Month 2 Sales`,
0 AS `Month 2 Profit`,
0 as `Month 3 Sales`,
0 AS `Month 3 Profit`
FROM
invline
JOIN invhead ON inh_invno = inl_invno
JOIN customer ON cus_custno = inh_custno
WHERE
YEAR(inh_date_printed) = YEAR(CURDATE()) AND MONTH( inh_date_printed ) =
1
GROUP BY
inh_custno
)
UNION
(
SELECT
cus_name AS Customer,
0,
0,
SUM(inl_qty * inl_unit_price) as `Month 2 Sales`,
SUM(inl_qty * inl_unit_price - inl_qty * inl_cost_price) AS `Month 2
Profit`,
0,
0
FROM
invline
JOIN invhead ON inh_invno = inl_invno
JOIN customer ON cus_custno = inh_custno
WHERE
YEAR(inh_date_printed) = YEAR(CURDATE()) AND MONTH( inh_date_printed ) =
2
GROUP BY
inh_custno
)
UNION
(
SELECT
cus_name AS Customer,
0,
0,
0,
0,
SUM(inl_qty * inl_unit_price) as `Month 3 Sales`,
SUM(inl_qty * inl_unit_price - inl_qty * inl_cost_price) AS `Month 3
Profit`
FROM
invline
JOIN invhead ON inh_invno = inl_invno
JOIN customer ON cus_custno = inh_custno
WHERE
YEAR(inh_date_printed) = YEAR(CURDATE()) AND MONTH( inh_date_printed ) =
3
GROUP BY
inh_custno
)
) AS combined
GROUP BY Customer
More information about the BNMlist
mailing list. Powered by Wessex Networks