如何在一个查询中加入一系列查询

时间:2015-06-11 15:39:42

标签: sql-server-2008

  

您好,

     

我有一系列查询(Q1,Q2,Q3,Q4 ....)和我的主查询(Query1)。   我想知道如何调用Q2和Q3 ....并将它们组合在Query1中。

     

查询(Q2)是主查询中使用的第一个查询   注意:Q6正在使用UNION。

-- Main Query1  
SELECT T1.ic, T1.itn, T1.ap, T1.oh FROM Q2 INNER JOIN T1 ON Q2.ic = T1.ic  

-- Q2
SELECT DISTINCT Q4.ic FROM Q3 RIGHT JOIN Q4 ON Q3.ic = Q4.ic WHERE Q3.ic is NULL

-- Q3
SELECT DISTINCT T2.ic, T2.Q FROM T2 INNER JOIN Q4 ON T2.ic = Q4.ic WHERE T2.s > GETDATE()


The Query1 returns the following table of results:

T1.ic       T1.itn      T1.ap     T1.oh     
2           LED         8          e
2           SCREW       3          f 
1           WASHER      1          g
6           RES         0          z
...     ...
...     ...
  

有人可以解释一下吗?    谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

这是一个使用CTE的解决方案

WITH Q3 (ic, Q) 
AS
(
    SELECT DISTINCT T2.ic, T2.Q 
    FROM T2 
    INNER JOIN Q4 ON T2.ic = Q4.ic 
    WHERE T2.s > GETDATE()
),
Q2 (ic)
AS
(

    SELECT DISTINCT Q4.ic 
    FROM Q3 
    RIGHT JOIN Q4 ON Q3.ic = Q4.ic 
    WHERE Q3.ic is NULL
)
SELECT T1.ic, T1.itn, T1.ap, T1.oh 
FROM Q2 
INNER JOIN T1 ON Q2.ic = T1.ic

答案 1 :(得分:0)

试试这个:

WITH Q3 AS 
(
SELECT DISTINCT T2.ic, T2.Q FROM T2 INNER JOIN Q4 ON T2.ic = Q4.ic WHERE T2.s > GETDATE()
), 
Q2 AS 
(
SELECT DISTINCT Q4.ic FROM Q3 RIGHT JOIN Q4 ON Q3.ic = Q4.ic WHERE Q3.ic is NULL
)
SELECT T1.ic, T1.itn, T1.ap, T1.oh FROM Q2 INNER JOIN T1 ON Q2.ic = T1.ic

您还可以使用嵌套的别名子查询,如下所示:

SELECT T1.ic, 
       T1.itn, 
       T1.ap, 
       T1.oh 
FROM   T1 
       JOIN (
             SELECT DISTINCT Q4.ic 
             FROM (
                   SELECT DISTINCT 
                          T2.ic, 
                          T2.Q 
                   FROM   T2 
                          INNER JOIN Q4 
                              ON T2.ic = Q4.ic 
                   WHERE  T2.s > GETDATE()
                  ) AS Q3 
                  RIGHT JOIN Q4 
                      ON Q3.ic = Q4.ic 
             WHERE Q3.ic is NULL
             ) AS Q2 
           ON Q2.ic = T1.ic