如何组合这两个SQL查询?

时间:2014-06-19 16:08:32

标签: sql tsql

我想要将两个SQL查询合并为1.这是当前(工作)查询:

select (
select sum(t3.unitWeight)
from t1
join t2 on t1.uid = t2.uid
join t3 on t3.partNo = t1.partNo 
where t1.prodDate = '6/11/14' 
) - (
select sum(t4.numPieces * t3.unitWeight)
from t1
join t4 on t1.uid = t4.uid
join t3 on t3.partNo = t1.partNo 
where t1.prodDate = '6/11/14' and t4.threadType = 'F'
)

(不幸的是,行扩展需要join t2...
我会以某种方式喜欢

SELECT SUM(t3.unitWeight - t4.numPieces * t3.unitWeight) ...

但当然这并不是很有效。感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

我应该想象下面的代码可以解决这个问题。我还没有机会测试这个。

BEGIN

DECLARE @UnitWeight DECIMAL
DECLARE @PiecesUnitWeight DECIMAL

SET @UnitWeight = 
(
    SELECT sum(t3.unitWeight)
    FROM t1
    JOIN t2 ON t1.uid = t2.uid
    JOIN t3 ON t3.partNo = t1.partNo 
    where t1.prodDate = '6/11/14' 
)

SET @PiecesUnitWeight = 
(
    SELECT sum(t4.numPieces * t3.unitWeight)
    from t1
    join t4 on t1.uid = t4.uid
    join t3 on t3.partNo = t1.partNo 
    where t1.prodDate = '6/11/14' and t4.threadType = 'F'
)

SELECT (@UnitWeight - @PiecesUnitWeight)

END

答案 1 :(得分:0)

您可以使用t1.uid字段加入两个选择..

SELECT   SUM( a.unitWeght1 - ISNULL(b.unitWeght2, 0)) as finalResult
FROM
    (
        select sum(t3.unitWeight) as unitWeght1, t1.uid
        from t1
        join t2 on t1.uid = t2.uid
        join t3 on t3.partNo = t1.partNo 
        where t1.prodDate = '6/11/14'
        GROUP BY    t1.uid
    )   a     left outer join           
    ( select sum(t4.numPieces * t3.unitWeight) as unitWeght2,  t1.uid
        from t1
        join t4 on t1.uid = t4.uid
        join t3 on t3.partNo = t1.partNo 
        where t1.prodDate = '6/11/14' and t4.threadType = 'F'
        GROUP BY    t1.uid 
    ) b on a.uid = b.uid