加入不同时间的表

时间:2017-09-14 14:05:34

标签: sql

我非常(非常)新编程,我想加入两个表。 如果我单独进行查询,它可以工作,但加入时我遇到了问题。 这是我到目前为止所做的:

SELECT DISTINCT(MCH_CODE) as Machine, COUNT(SELL) AS Sells
FROM SELLS
WHERE STATUS = 'SOLD' AND SUBCODE = 'T'  
AND TIME >='2017-09-14 07:00:00' and STORE_CODE ='A101'
GROUP BY MCH_CODE

第二个:

SELECT DISTINCT(MCH_CODE) as Machine,  COUNT(BARCODES) AS Scanned
FROM SCANNED_TABLE
WHERE TIME_STAMP >= '2017-09-14 07:00:00' AND STORE_CODE ='A101' 
GROUP BY MCH_CODE

这就是我到目前为止所得到的:

SELECT DISTINCT (dc.MCH_CODE) as Machine, COUNT(dc.SELL) AS Sells, COUNT(BARCODES) AS Scanned
FROM SELLS AS dc
INNER JOIN SCANNED_TABLE AS tr
ON dc.STORE_CODE = tr.STORE_CODE
WHERE dc.STATUS = 'SOLD' AND dc.SUBCODE = 'T'  
AND dc.TIME >='2017-09-14 07:00:00' and dc.STORE_CODE ='A101'
GROUP BY dc.MCH_CODE

我应该得到类似的东西 机器销售扫描但当我加入表格时,值不一样。 是因为时代吗?如何正确加入表?

2 个答案:

答案 0 :(得分:1)

您已经拥有了所有需要,可以将它们作为子查询加入

SELECT t1.Machine, t1.Sells, t2.Scanned
FROM
    (SELECT MCH_CODE as Machine, COUNT(SELL) AS Sells
     FROM SELLS
     WHERE STATUS = 'SOLD' AND SUBCODE = 'T'  
     AND TIME >='2017-09-14 07:00:00' and STORE_CODE ='A101'
     GROUP BY MCH_CODE) t1 
    INNER JOIN
    (SELECT MCH_CODE as Machine,  COUNT(BARCODES) AS Scanned
     FROM SCANNED_TABLE
     WHERE TIME_STAMP >= '2017-09-14 07:00:00' AND STORE_CODE ='A101' 
     GROUP BY MCH_CODE) t2 ON t1.Machine=t2.Machine

答案 1 :(得分:0)

尝试将两个语句连接在一起,而不是创建组合连接。

试试这个:

SELECT
    *
FROM 
(
SELECT
    MCH_CODE AS Machine
    ,STORE_CODE
    ,COUNT(SELL) AS Sells
FROM
    SELLS
WHERE 
    STATUS = 'SOLD'
    AND SUBCODE = 'T'
    AND TIME >= '2017-09-14 07:00:00'
    AND STORE_CODE = 'A101'
GROUP BY
    MCH_CODE
) AS A
INNER JOIN (
SELECT
    MCH_CODE AS Machine
    ,STORE_CODE
    ,COUNT(BARCODES) AS Scanned
FROM
    SCANNED_TABLE
WHERE 
    TIME_STAMP >= '2017-09-14 07:00:00'
    AND STORE_CODE = 'A101'
GROUP BY
    MCH_CODE
) AS B ON A.STORE_CODE = B.STORE_CODE AND A.Machine = B.Machine