通过SPECIFIC CRITERIA加入两个复杂SQL查询的结果

时间:2016-07-19 06:23:40

标签: c# sql sql-server

有两个查询,下面是查询以及案例中的结果。

在第一个查询结果中,在第5行,从南行到北行,有5辆半卡车,第7行有22辆卡车。

第二个查询中,有两种对象类型。如果我们考虑第4排,那行说,从南行到北行,有3辆半卡车和3辆卡车

要做的是,从第2个结果得到3 Semitruck,它们将在第一个查询的第5行的新结果中加起来。因此,半卡车总数将为8辆,同样,卡车将为25辆(第7排)

此外,如果没有公共行,则会将其添加为结果中的新行。

第一名:

select 
    count(v.ObjectType) o, 
    v.ObjectType, v.EnterDirection, v.Direction 
from 
    validobjects v 
where 
    processinfoid = 1 
    and Isactive = 1 
    and v.ObjectType <> 'None' 
    and (v.EnterDirection = 'SouthBound' OR 
         v.EnterDirection = 'EastBound' OR 
         v.EnterDirection = 'NorthBound' OR 
         v.EnterDirection = 'WestBound' OR 
         v.EnterDirection = 'SouthEastBound' OR 
         v.EnterDirection = 'SouthWestBound' OR 
         v.EnterDirection = 'NorthEastBound' OR 
         v.EnterDirection = 'NorthWestBound')
group by 
    v.ObjectType, v.EnterDirection, v.Direction

结果:

enter image description here

第二

select 
    count(v.objecttype1) o1,
    count(v.ObjectType2) o2, 
    v.ObjectType1, v.ObjectType2, 
    v.EnterDirection, v.Direction 
from 
    ValidObjects v 
where 
    v.ValidObjectID in (select ValidObjectID 
                        from validobjects v 
                        where processinfoid = 1 
                          and Isactive = 1 
                          and ObjectType = 'None' )
group by 
    v.ObjectType1, v.ObjectType2, v.EnterDirection, v.Direction

结果

enter image description here

1 个答案:

答案 0 :(得分:0)

试试这个

SELECT
    * -- Your operation
FROM
(
    SELECT * FROM FirstQuery
) FQ LEFT JOIN 
(
    SELECT * FROM SecondQuery
) SQS ON FQ.ObjectType = SQS.ObjectType1 AND 
         FQ.EnterDirection = SQS.EnterDirection AND 
         FQ.Direction = SQS.Direction -- SemiTruck
LEFT JOIN 
(
    SELECT * FROM SecondQuery
) SQT ON 
        FQ.ObjectType = SQT.ObjectType2 AND 
        FQ.EnterDirection = SQT.EnterDirection AND 
        FQ.Direction = SQT.Direction -- Truck