我想从链接到另一个表的表中总结价格。
我尝试这个查询:
SELECT COUNT(cmd.mt14),
SUM(cmd.mt14)
FROM g_piece cmd
INNER JOIN g_piece lot
ON lot.GPIREFNOTAIRE = cmd.refpiece
AND lot.gpirole = 'B2029005'
结果是:
count(cmd.mt14) sum(cmd.mt14)
100 170704,188
这并不好,因为它因左连接而对所有重复的行进行求和。 如果我尝试“独特”:
SELECT count(unique cmd.mt14),
sum(unique cmd.mt14)
FROM g_piece cmd
INNER JOIN g_piece lot
ON lot.GPIREFNOTAIRE = cmd.refpiece
AND lot.gpirole = 'B2029005'
结果:
count(unique cmd.mt14) sum(unique cmd.mt14)
54 57724,554
问题在于,这也是错误的,因为总和函数并不是所有价格的总和,而是唯一的价格。
如何根据不同的栏目汇总所有价格?
非常感谢
如果我尝试在Excel上获取行和SUM所有行,我有:
count sum
58 58492.503
答案 0 :(得分:1)
你的第二个" LEFT JOIN"必须始终满足,因为您在WHERE子句中使用其中一个列。而你根本就没有使用IND表。那么为什么不呢:
SELECT count(cmd.mt14),
sum(cmd.mt14)
FROM g_piece cmd
INNER JOIN g_piece lot
ON lot.GPIREFNOTAIRE = cmd.refpiece
WHERE lot.gpirole = 'B2029005'
如果那不是你要找的东西,那么也许你只是想验证你的CMD是否存在于特定的地段:
SELECT count(cmd.mt14),
sum(cmd.mt14)
FROM g_piece cmd
WHERE EXISTS (select 1 from g_piece lot
where lot.GPIREFNOTAIRE = cmd.refpiece
AND lot.gpirole = 'B2029005')
答案 1 :(得分:0)
我看到两个问题:
。
SELECT count_mt14, sum_mt14
FROM (SELECT count(cmd.mt14) count_mt14, sum(mt14) sum_mt14, Liebelle_20_1
FROM g_Piece group by liebelle_20_1) cmd
LEFT JOIN g_individu ind
ON ind.refindividu = cmd.LIBELLE_20_1
LEFT JOIN g_piece lot
ON lot.GPIREFNOTAIRE = cmd.refpiece
AND lot.gpirole = 'B2029005'
答案 2 :(得分:0)
非常感谢您的所有帮助,最后我对此查询做了以下的事情:
SELECT SUM(comm.mt14),
COUNT(comm.refpiece)
FROM
(
SELECT UNIQUE cmd.refpiece,
cmd.mt14
FROM g_piece cmd
INNER JOIN g_piece lot
ON lot.GPIREFNOTAIRE = cmd.refpiece
WHERE lot.gpirole = 'B2029005'
) comm