SQL查询 - 左连接组

时间:2017-11-02 15:23:30

标签: sql sql-server

我有两张桌子:

第一个用于接收详细信息,第二个用于接收标题。

CREATE TABLE ACH_ReceptionsDet
(
    IdReception bigint NOT NULL,
    IdProd bigint,
    QteRecue numeric(16,5),
);

CREATE TABLE ACH_ReceptionsEnt
(
    IdReception bigint PRIMARY KEY NOT NULL,
    DateRec datetime NOT NULL,
);

我想为每个IdProd获得最后一个IdProd,QteRecue,DateRec。 换句话说,我想最后接收每种产品。

编辑:

现在我能够像这样(4862结果)获得DateRecep和IdProd:

SELECT
  MAX(E.DateRec) AS DateRecp,
  D.IdProd
FROM ogasys.ACH_ReceptionsDet D
  LEFT JOIN ogasys.ACH_ReceptionsEnt E
    ON D.IdReception = E.IdReception
GROUP BY D.IdProd

我无法在select中添加D.QteRecue,因为它不包含在聚合函数或GROUP BY子句中。我不明白该怎么做。

如果我运行此查询(4862结果)

SELECT count(DISTINCT Idprod)
FROM ogasys.ACH_ReceptionsDet

但如果我添加E.QteRecue (6973结果)

SELECT
      MAX(E.DateRec) AS DateRecp,
      D.IdProd,
      **E.QteRecue**
    FROM ogasys.ACH_ReceptionsDet D
      LEFT JOIN ogasys.ACH_ReceptionsEnt E
        ON D.IdReception = E.IdReception
    GROUP BY D.IdProd, **E.QteRecue**

3 个答案:

答案 0 :(得分:1)

将列添加到组中应解决问题:

SELECT
  MAX(E.DateRec) AS DateRecp,
  D.IdProd,
  D.QteRecue
FROM ogasys.ACH_ReceptionsDet D
  LEFT JOIN ogasys.ACH_ReceptionsEnt E
    ON D.IdReception = E.IdReception
GROUP BY D.IdProd, D.QteRecue;

答案 1 :(得分:0)

您似乎想要row_number()

SELECT de.*
FROM (SELECT DateRecp, D.IdProd, D.QteRecue,
             ROW_NUMBER() OVER (PARTITION BY D.IdProd ORDER BY DateRecp DESC) as seqnum
      FROM ogasys.ACH_ReceptionsDet D LEFT JOIN
           ogasys.ACH_ReceptionsEnt E
           ON D.IdReception = E.IdReception
     ) de
WHERE seqnum = 1;

答案 2 :(得分:0)

您可以像这样使用子查询

    SELECT temp.DateRecp,
        ,temp.IdProd
        ,R.QteRecue
FROM ogasys.ACH_ReceptionsDet R 
INNER JOIN
    (SELECT MAX(E.DateRec) AS DateRecp
            ,D.IdProd  
    FROM ogasys.ACH_ReceptionsDet D
    LEFT JOIN ogasys.ACH_ReceptionsEnt E ON D.IdReception = E.IdReception
    GROUP BY D.IdProd) AS temp ON R.IdProd = temp.IdProd