如何加入两个选择语句

时间:2016-05-17 07:38:54

标签: sql sql-server date

我有四张桌子。我独立编写了2个查询,这些查询正在运行。但我想要做的是加入这两个查询并生成一个结果。

这是我的代码

查询#1

SELECT 
    pm.DATE
    ,pm.customer
    ,pm.gp_no AS Gatepass_Num
    ,pf.style
    ,pf.color
    ,pf.batch_no
    ,COUNT(pf.roll_no) AS Roll_QTY
    ,SUM(pf.meter) AS QTY
FROM
    (packinglists_fabrics_items pf
     ,packinglists_main pm 
WHERE 
    pf.p_id = pm.id 
    [AND pm.date between {DateR,RANGE1} and {DateR,RANGE2}] 
    [AND pm.customer_id = "{factory,false}"]
GROUP BY 
    pm.DATE, pm.gp_no, pf.style, pf.color, pf.batch_no)

查询#2:

SELECT 
    lo.DATE
    ,lo.customer_name
    ,flo.style
    ,flo.color
    ,flo.batch_no
    ,COUNT(flo.rowno) AS Roll_QTY
    ,SUM(flo.meter) AS QTY_Meter
FROM
    loadinglists_fabrics_items flo, loadinglists lo
WHERE 
    flo.p_id = lo.id 
    [AND lo.date between {DateR,RANGE1} and {DateR,RANGE2}] 
    [AND lo.customer_id = "{factory,false}"]
GROUP BY 
    lo.DATE, flo.style, flo.color, flo.batch_no

batch_no对于loadinglists_fabrics_items表和packinglists_fabrics_items

是唯一的

查询1的结果

enter image description here

查询2的结果

enter image description here

预期输出

enter image description here

1 个答案:

答案 0 :(得分:2)

尝试这样,我假设您使用的是SQL Server

SELECT A.*
    ,B.*
FROM (
    SELECT pm.DATE
        ,pm.customer
        ,pm.gp_no AS Gatepass_Num
        ,pf.style
        ,pf.color
        ,pf.batch_no
        ,COUNT(pf.roll_no) AS Roll_QTY
        ,SUM(pf.meter) AS QTY
    FROM packinglists_fabrics_items pf
        ,packinglists_main pm
    WHERE pf.p_id = pm.id
        AND pm.DATE BETWEEN {DateR
                ,RANGE1}
            AND {DateR
                ,RANGE2}
        AND pm.customer_id = "{factory,false}"
    GROUP BY pm.DATE
        ,pm.gp_no
        ,pf.style
        ,pf.color
        ,pf.batch_no
    ) A
INNER JOIN (
    SELECT lo.DATE
        ,lo.customer_name
        ,flo.style
        ,flo.color
        ,flo.batch_no
        ,COUNT(flo.rowno) AS Roll_QTY
        ,SUM(flo.meter) AS QTY_Meter
    FROM loadinglists_fabrics_items flo
        ,loadinglists lo
    WHERE flo.p_id = lo.id
        AND lo.DATE BETWEEN {DateR
                ,RANGE1}
            AND {DateR
                ,RANGE2}
        AND lo.customer_id = "{factory,false}"
    GROUP BY lo.DATE
        ,flo.style
        ,flo.color
        ,flo.batch_no
    ) B ON A.batch_no = B.batch_no