我有以下SQL查询:
SELECT porel.refcode, podetail.ponum, SUM(podetail.orderqty * podetail.unitcost) AS Total
FROM podetail
LEFT JOIN porel ON podetail.ponum = porel.ponum
WHERE porel.poline=podetail.poline AND porel.reftype = 'SPEX'
GROUP BY porel.refcode, podetail.ponum
ORDER BY porel.refcode, podetail.ponum
可以很好地为我提供ponums
的列表及其对refcodes
的总价值。
我现在要添加第三列vendor.name
。 vendor
表有一个字段vendorid
,它与podetail
表共享。
有多个podetail
条记录具有相同的ponum
,但这些记录也会匹配vendorid
。
有人可以建议我如何在vendor.name
字段中添加而不返回额外的行吗?
答案 0 :(得分:2)
将其添加到GROUP BY
。我假设每个podetail.ponum
都会有一个供应商。顺便说一下,由于Where子句中的porel.reftype = 'SPEX'
,当前查询将左连接转换为内连接。
SELECT porel.refcode,
podetail.ponum,
SUM(podetail.orderqty * podetail.unitcost) AS Total,
vendor.name
FROM podetail
INNER JOIN vendor ON podetail.vendorid = vendor.vendorid
LEFT JOIN porel ON podetail.ponum = porel.ponum
WHERE porel.poline=podetail.poline
AND porel.reftype = 'SPEX'
GROUP BY porel.refcode,
podetail.ponum,
vendor.name
ORDER BY porel.refcode,
podetail.ponum
答案 1 :(得分:2)
Heya,Rogue。我想说的不仅仅是评论,所以在这里。
另一个更容易诊断的问题是:
SELECT
porel.refcode,
podetail.ponum,
SUM(podetail.orderqty * podetail.unitcost) AS Total,
podetail.vendorid
FROM
podetail
LEFT JOIN porel
ON podetail.ponum = porel.ponum
WHERE
porel.poline = podetail.poline
AND porel.reftype = 'SPEX'
GROUP BY
porel.refcode,
podetail.ponum,
podetail.vendorid
ORDER BY
refcode,
ponum
在这里,我们根本没有加入vendor
,完全不在等式中。相反,我们只需汇总podetail.vendorid
。
您可以发布此查询的输出吗?
答案 2 :(得分:0)
SELECT porel.refcode,
podetail.poline,
podetail.ponum,
SUM(podetail.orderqty * podetail.unitcost) AS Total,
vendor.name
FROM podetail
INNER JOIN vendor ON podetail.vendorid = vendor.vendorid
LEFT JOIN porel ON podetail.ponum = porel.ponum
WHERE porel.poline=podetail.poline
AND porel.reftype = 'SPEX'
GROUP BY porel.refcode,
podetail.ponum,
vendor.name
ORDER BY porel.refcode,
podetail.poline,
podetail.ponum
我认为,您无需在podetail.poline
和SELECT
中加入GROUP BY
。
答案 3 :(得分:0)
由于您正在聚合podetails,只需汇总供应商名称:
SELECT porel.refcode, podetail.ponum
, MAX(vendor.name) as VendorName
, SUM(podetail.orderqty * podetail.unitcost) AS Total
FROM podetail
LEFT JOIN vendor on podetail.vendorid = vendor.vendorid
LEFT JOIN porel ON podetail.ponum = porel.ponum
WHERE porel.poline=podetail.poline AND porel.reftype = 'SPEX'
GROUP BY porel.refcode, podetail.ponum
ORDER BY porel.refcode, podetail.ponum
如果您愿意,可以使用MIN()。