我正在创建一个查询,该查询将按月显示预计的数量与数量。下面是我的两个表,第三个是我想要的输出。这两个表几乎相同,只是日期和创建日期是不同的格式(我已将其转换为输出,例如201301,所以不用担心它)。 正如你在我的输出表中注意到的那样,售出的数量变为25.00,因为如果日期属于同一个月和年份,它会增加数量。我还需要考虑以下三个重要条件:
我不知道我是否必须使用join或union来实现我想要的输出。
表A(销售表)
item code Sold date
001 cust001 10.00 2013-01-20
001 cust001 15.00 2013-01-25
040 cust045 16.00 2013-04-07
312 cust001 20.00 2013-03-13
表B(投影表)
item Custcode ProjectedQty Creation Date
001 cust001 20.00 2013-01-01
040 cust045 50.00 2013-04-01
206 cust121 60.00 2013-04-01
输出
item Custcode sold Date ProjectedQty Creation Date
001 cust001 25.00 201301 20.00 201301
312 cust001 20.00 201303 null null
040 cust045 16.00 201304 50.00 201304
206 cust121 null null 60.00 201304
感谢各位帮忙。
答案 0 :(得分:1)
为什么不为此使用简单的加入?
SELECT * FROM `sales`, `projection` WHERE `code`=`custcode`;
对上面的查询进行查看,并使用WHERE
子句,您可以更改数据。
答案 1 :(得分:1)
尝试
SELECT COALESCE(p.item, s.item) item,
COALESCE(p.code, s.code) code,
sold,
CONCAT(s.year, LPAD(s.month, 2, '0')) date,
ProjectedQty,
CONCAT(p.year, LPAD(p.month, 2, '0')) creationdate
FROM
(
SELECT item, code, YEAR(`date`) year, MONTH(`date`) month
FROM sales
UNION
SELECT item, custcode, YEAR(`creationdate`), MONTH(`creationdate`)
FROM projection
) i LEFT JOIN
(
SELECT item, code, SUM(sold) sold, YEAR(`date`) year, MONTH(`date`) month
FROM sales
GROUP BY item, code, YEAR(`date`), MONTH(`date`)
) s ON i.item = s.item
AND i.code = s.code
AND i.year = s.year
AND i.month = s.month LEFT JOIN
(
SELECT item, custcode code, SUM(ProjectedQty) ProjectedQty, YEAR(`creationdate`) year, MONTH(`creationdate`) month
FROM projection
GROUP BY item, custcode, YEAR(`creationdate`), MONTH(`creationdate`)
) p ON i.item = p.item
AND i.code = p.code
AND i.year = p.year
AND i.month = p.month
ORDER BY code, item
输出:
| ITEM | CODE | SOLD | DATE | PROJECTEDQTY | CREATIONDATE |
------------------------------------------------------------------
| 001 | cust001 | 25 | 201301 | 20 | 201301 |
| 312 | cust001 | 20 | 201303 | (null) | (null) |
| 040 | cust045 | 16 | 201304 | 50 | 201304 |
| 206 | cust121 | (null) | (null) | 60 | 201304 |
<强> SQLFiddle 强>
答案 2 :(得分:0)
使用union创建视图。然后你可以使用以下查询:
select *, sum(sold) as sold from view group by item
另一个是:
select *, sum(sold) from (
select item, code as Custcode, sold, date, 'ProjectedQty' as ProjectedQty, 'Creation Date' as Creation Date from table 1 union select item, Custcode, sold, Date, ProjectedQty, Creation Date, from table 2) group by item