我又来了另一个问题/问题。我知道这个主题的标题可能和其他人一样,但我注意到他们还有其他问题。
我有一个SQL LEFT JOIN的问题。我正在使用MySQL。
我希望有一个表格,其中TYPES将持续六个月并计算一个月(它可能看起来很奇怪,但我出于某些目的需要它。)
我有两个查询(我会显示查询和输出,它会更具体)。
首次查询为期六个月:
SELECT objectsoort AS types, COUNT(objectsoort) AS total, prijs AS price, SUM(prijs)/ SUM(oppervlakte) AS meters
FROM `huislijn`
WHERE <clause statements>
GROUP BY objectsoort
我得到的结果如下:
Six_months http://i56.tinypic.com/14ag1zs.png
第二次查询是一个月:
SELECT objectsoort AS types1, COUNT(objectsoort) AS total1, AVG(prijs) AS price1, SUM(prijs)/ SUM(oppervlakte) AS meters1
FROM `huislijn`
WHERE <clause statements>
GROUP BY objectsoort
然后我得到这样的结果:
One month http://i53.tinypic.com/i20haa.png
我想把它们作为一个,所以我使用LEFT JOIN并得到这样的查询:
SELECT a.types1, b.total1, b.price1, b.meters1
FROM (SELECT objectsoort AS types1
FROM `huislijn`
WHERE <clause statements> ) a
LEFT JOIN
(SELECT objectsoort AS types12, COUNT( objectsoort ) AS total1, AVG( prijs ) AS price1, SUM( prijs ) / SUM( oppervlakte ) AS meters1
FROM `huislijn`
WHERE <clause statements> ) b
ON a.types1 = b.types12
GROUP BY types1
但结果不是我所期望的,因为'appartement'附近应该有一些结果,并且'wining'结果与查询中的结果不同一个月:
both in one http://i54.tinypic.com/20qcj8w.png
我再说一遍:我想要六个月的类型和一个月的计算。在这种情况下,它意味着结果应该接近'appartement'和'woning'。
所以,我想知道,也许我做错了什么。
感谢您的帮助和支持。
答案 0 :(得分:1)
好的,我被要求分享解决方案,所以这里是:
正如 cularis 所说,我在某些地方错过了GROUP BY objectsoort
。有工作查询(我已经改变了一点,因为正在处理它,但结果仍然是相同的):
SELECT a.types5, b.total5, b.price5, b.meters5, a.total, a.price, a.meters
FROM (
SELECT objectsoort AS types5, COUNT(objectsoort) AS total, prijs AS price, SUM(prijs)/SUM(oppervlakte) AS meters
FROM `huislijn`
WHERE <clause statements>
GROUP BY objectsoort ) a
LEFT JOIN (
SELECT objectsoort AS types15, COUNT(objectsoort) AS total5, AVG(prijs) AS price5, SUM(prijs)/SUM(oppervlakte) AS meters5
FROM `huislijn`
WHERE <clause statements>
GROUP BY objectsoort ) b
ON a.types5 = b.types15
GROUP BY types5
结果:
result http://i51.tinypic.com/1z5onxy.png
感谢 cularis !