我需要一起加入两份报告......
第一个表“订单”包含许多记录的字段,如:
id|ContractDate|TotalPrice
--------------------------
5 |2015-01-03 |200.30
4 |2015-12-28 |100.70
3 |2014-01-03 |150.30
2 |2014-12-28 |30.70
1 |2013-10-02 |50.20
第一个sql显示:
Year|Turnover|Quantity|EurPerOrder
---------------------------------
2015|301.00 |2 |150.50
2014|181.00 |2 |90.50
2013|50.20 |1 |50.20
第二个表“项目”包含许多记录的字段,如:
requestid | Date |Price
-------------------------------
5 |2015-01-03 |2000.00
4 |2015-12-28 |1000.00
3 |2014-12-01 |5000.00
2 |2012-12-02 |4000.00
1 |2012-12-28 |6000.00
第二个sql显示:
Year|Turnover|Quantity|EurPerOrder
----------------------------------
2015|3000.00 |2 |1500.00
2014|5000.00 |1 |5000.00
2012|10000.00|2 |50000.00
我想在一个列表中显示两个表数据,如:
Year|TurnoverOftable1|QuantityOftable1|EurPerOrderOftable1|TurnoverOftable2|QuantityOftable2|EurPerOrderOftable2
------------------------------------------------------------------------------------------------------------------
2015|301.00 |2 |150.50 |3000.00 |2 |1500.00
2014|181.00 |2 |90.50 |5000.00 |1 |5000.00
2013|50.20 |1 |50.20 |* |* |*
2012|* |* |* |10000.00 |2 |50000.00
“*”为0或NULL
第一个sql代码是:
SELECT Year(orders.date) AS Year,
Sum(orders.price) AS Turnover,
Count(orders.requestid) AS Quantity,
ROUND(Sum(orders.price) / Count(orders.requestid), 0) AS EurPerOrder
FROM orders
GROUP BY Year(orders.date) * 100
ORDER BY orders.date DESC
第二个sql代码是:
SELECT Year(projects.ContractDate) AS Year,
Sum(projects.TotalPrice) AS Turnover,
Count(projects.id) AS Quantity,
ROUND(Sum(projects.TotalPrice) / Count(projects.id), 0) AS EurPerOrder
FROM projects
GROUP BY Year(projects.ContractDate) * 100
ORDER BY projects.ContractDate DESC
我的sql分组按年份显示所有列,但计算错误:
SELECT
Year(orders.date) AS Year,
Sum(orders.price) AS TurnoverOftable1,
Count(orders.requestid) AS QuantityOftable1,
ROUND(Sum(orders.price) / Count(orders.requestid), 0) AS EurPerOrderOftable1,
Sum(projects.TotalPrice) AS TurnoverOftable2,
Count(projects.id) AS QuantityOftable2,
ROUND(Sum(projects.TotalPrice) / Count(projects.id), 0) AS EurPerOrderOftable2
FROM
orders
LEFT JOIN projects
ON Year(orders.date) = Year(projects.ContractDate)
GROUP BY
Year(orders.date) * 100, Year(projects.ContractDate) * 100
ORDER BY
orders.date DESC, projects.ContractDate DESC
如果有人帮助我加入这两份报告,我会非常感激!提前谢谢你......
答案 0 :(得分:1)
尝试以下内容:
SELECT q1.Year, q1.Turnover, q1.Quantity, q1.EurPerOrder, q2.Turnover, q2.Quantity, q2.EurPerOrder
FROM (SELECT Year(orders.date) AS Year,
Sum(orders.price) AS Turnover,
Count(orders.requestid) AS Quantity,
ROUND(Sum(orders.price) / Count(orders.requestid), 0) AS EurPerOrder
FROM orders
GROUP BY Year(orders.date) * 100
ORDER BY orders.date DESC ) as q1
LEFT JOIN
(SELECT Year(projects.ContractDate) AS Year,
Sum(projects.TotalPrice) AS Turnover,
Count(projects.id) AS Quantity,
ROUND(Sum(projects.TotalPrice) / Count(projects.id), 0) AS EurPerOrder
FROM projects
GROUP BY Year(projects.ContractDate) * 100
ORDER BY projects.ContractDate DESC) as q2
ON q1.Year = q2.Year