简体   繁体   中英

How to combine these 2 SQL queries?

I have two SQL queries I would like to combine into 1. Here is the current (working) query:

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'
)

(Unfortunately, the join t2... is required for row expansion)
I would somehow like to have

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

but of course that doesn't quite work. Thanks for any assistance.

I should imagine something like the below code would do the trick. I haven't had chance to test this.

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

You could use the t1.uid field to join the two selects..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM