我试图以三种不同的方式从一列中获取数据。我正在处理供应商报价和客户接受的报价(然后成为项目)。
我想从他们所有的项目中获得总节省额,无论是否完成。其次,我们正在抓住当前的储蓄,即当前开放项目的储蓄。最后,我需要找出提供给他们但他们尚未采取行动的总金额。
我已经处理了这个查询的前两个:
SELECT SUM(osh.Savings) as YTD,
SUM(case when p.current_status < 3 then Savings end) AS "Open Savings"
FROM OfferSuggestionHeader osh LEFT JOIN
Projects p
ON p.offer_id = osh.OfferID
WHERE p.uid = '1'
到现在为止还挺好。当我开始加入必要的表格以抓住最后一块时,问题就出现了。这是单数查询的样子(并且有效):
SELECT SUM(ofh.Savings)
from OfferSuggestionHeader ofh
LEFT JOIN OfferSuggestionDetail osd
on ofh.OfferID = osd.OfferID
LEFT JOIN Facilities f
on osd.FacilityID = f.id
LEFT JOIN UserFacility uf
on f.id = uf.fid
LEFT JOIN Users u
on uf.uid = u.uid
WHERE u.uid = 1
AND ofh.OfferID NOT IN(SELECT offer_id FROM Projects WHERE uid = 1)
我尝试了六种不同的混合方式,但都以失败告终。似乎它正在多次将数字相加或类似的东西。
感谢您的任何帮助或指点。
编辑: - - - - - - - -
因此,这是一个查询,它执行必要的连接以尝试在保持CASE
语句存在的同时获得这么大的总数:
SELECT (osh.Savings) as "Potential",
(case when p.current_status < 3 then osh.Savings else null end) AS "Open Savings",
(case when p.uid=1 then osh.Savings else null end) AS "YTD"
FROM OfferSuggestionHeader osh
LEFT JOIN OfferSuggestionDetail osd
ON osd.OfferID = osh.OfferID
LEFT JOIN UserFacility uf
ON uf.fid = osd.FacilityID
LEFT JOIN Projects p
ON p.uid = uf.uid
WHERE p.uid = '1'
我已经删除了这一SUM
部分,看看会发生什么,正如你们中的一些人所建议的那样。果然,我得到了每个值的三个记录。
这是否有助于更好地澄清问题?
编辑#2:------------ 根据要求,这里是单独的工作查询:
年初至今:
/*YTD Savings*/
SELECT SUM(osh.Savings) as YTD
FROM Projects p
LEFT JOIN OfferSuggestionHeader osh
ON p.offer_id = osh.OfferID
WHERE p.uid = 1
当前活动/打开:
/*total from open projects*/
SELECT SUM(osh.Savings) as TotalOpen
FROM Projects p
LEFT JOIN OfferSuggestionHeader osh
ON p.offer_id = osh.OfferID
WHERE p.uid = 1 AND p.current_status < 3
最后,潜在节省的总和:
/*POTENTIAL*/
SELECT SUM(ofh.Savings) as Potential
from OfferSuggestionHeader ofh
LEFT JOIN OfferSuggestionDetail osd
on ofh.OfferID = osd.OfferID
LEFT JOIN Facilities f
on osd.FacilityID = f.id
LEFT JOIN UserFacility uf
on f.id = uf.fid
LEFT JOIN Users u
on uf.uid = u.uid
WHERE u.uid = 1
AND ofh.OfferID NOT IN(SELECT offer_id FROM Projects WHERE uid = 1)