非程序员无法获得具有聚合总和的子查询

时间:2017-02-27 19:29:05

标签: sql

我有2个查询需要在一行上链接在一起:

SELECT pvp.part_no, pvp.name,
    Max(convert(varchar(10), pc.recalc_date, 101)) as 'Previous Cost Date',
    Max(pc.cost) as 'Previous Cost',
    Min(convert(varchar(10),pc2.recalc_date, 101)) as 'Latest Cost Date',
    Min (pc2.cost) as 'Latest Cost'
FROM part_v_part as pvp
JOIN part_v_part_cost as pc ON pvp.part_key = pc.part_key
Left outer join part_v_part_cost as pc2 on
pvp.part_key = pc2.part_key and
pc2.recalc_date > pc.recalc_date
Join part_v_container pvc on pc.part_key = pvc.part_key
WHERE pvp.part_status <> 'inactive'
AND pvp.part_status <> 'obsolete'       
AND pc2.recalc_date between '1/01/2017' and '1/31/2017'
AND pvc.active = 1
AND pvc.container_status = 'OK'
AND pvp.part_no = '90-0018'
GROUP BY pvp.part_no, pvp.name, pvp.part_key

-- =====================================================================

SELECT PVP1.Part_No AS 'Part No',
    PVp1.Name AS 'Description', 
    PVP1.Revision AS 'Rev',
    SUM(pvc1.quantity ) AS 'QOH at cost update'
FROM Part_V_Container pvc1
JOIN Part_V_Part pvp1 ON pvc1.Part_Key = pvp1.Part_Key
WHERE pvc1.active = 1
AND pvc1.container_status = 'OK'
AND pvc1.add_date <= '1/6/17'
AND pvp1.part_no = '90-0018' 
GROUP BY PVP1.Part_No,PVP1.Name, PVP1.Revision

以下是我的2个查询的结果。我需要将QOH在成本更新字段中从第二个查询集成到第一个查询中。 我已经花了几天时间研究这个问题,并且我总是遇到像子查询不能包含聚合函数这样的错误。

更糟糕的是我正在使用的sql工具嵌入到ERP系统中,因此我不知道正在使用哪个版本的SQL。我能说的最好的是TSQL?

part_no | name                     | Previous Cost Date | Previous Cost | Latest Cost Date  | Latest Cost
1       | 90-0018   PISTON, DRIVEN | 07/19/2016         |  28.93685     | 01/06/2017        | 39.16178

行数:1

零件编号描述Rev QOH成本更新

1 90-0018 PISTON,驾驶51.00000 行数:1

1 个答案:

答案 0 :(得分:0)

如果我了解需要,你必须:

SELECT * FROM
(
Paste first query here
) a
JOIN
(
Paste second query here
) b
ON a.part_no = b.[Part No]

这将为您提供使用part_no值

连接的两个查询的所有列

希望这有帮助