根据日期

时间:2016-07-20 18:12:21

标签: sql sql-server sql-view

您好我正在使用此查询根据最近的日期选择属于实体的文章:

SELECT DISTINCT ld.artigo, 
                cd.data, 
                cd.entidade, 
                cd.tipodoc, 
                cd.numdoc 
FROM   cabecdoc AS cd 
INNER JOIN linhasdoc AS ld 
        ON cd.id = ld.idcabecdoc 
INNER JOIN cabecdocstatus AS cds 
        ON ld.idcabecdoc = cds.idcabecdoc 
WHERE  cd.tipodoc = 'FAR' 
       AND ld.artigo IS NOT NULL 
       AND cds.estado <> 't;r' 
ORDER  BY cd.data DESC 

让我假设我有这个结果

Artigo  Entidade         Data
Tr01    002              10-07-2015
Tr01    003              9-10-2015
Mn09    001              11-12-2016
Jk90    009              12-07-2016
Tr01    012              4-09-2016

我正在寻找的结果是:

Artigo                   entidade                             data
Mn09                      0001                                  11-12-2016
Jk90                      0009                               2-07-2016
Tr01                      0012                               4-09-2016

非常感谢!

3 个答案:

答案 0 :(得分:1)

您可以在ROW_NUMBER()上使用带有PARTITION的窗口artigo功能来确定哪一个是最新的,并且只提取这些结果。

;With Cte As
(
    SELECT ld.artigo
        ,cd.data
        ,cd.entidade
        ,cd.tipodoc
        ,cd.numdoc
        ,Row_Number() Over (Partition By ld.artigo Order By cd.data desc) As Seq
    FROM CabecDoc AS cd
    INNER JOIN LinhasDoc AS ld ON cd.id = ld.IdCabecDoc
    INNER JOIN CabecDocStatus AS cds ON ld.IdCabecDoc = cds.IdCabecDoc
    WHERE cd.TipoDoc = 'FAR'
        AND ld.Artigo IS NOT NULL
        AND cds.Estado <> 't;r'
)
Select  artigo, entidade, data
From    Cte
Where   Seq = 1

答案 1 :(得分:0)

使用结果查询作为基础来创建新的

 SELECT Artigo, Entidade, Data
 FROM (  
        SELECT *, ROW_NUMBER() OVER (PARTITION BY Artigo ORDER BY Data DESC) as rn
        FROM YourQuery YQ
      ) T
 WHERE T.rn = 1

答案 2 :(得分:0)

您可以使用以下窗口功能

来实现此目的
;WITH CTE AS (
SELECT DISTINCT ld.artigo, 
                cd.data, 
                cd.entidade, 
                cd.tipodoc, 
                cd.numdoc 
FROM   cabecdoc AS cd 
INNER JOIN linhasdoc AS ld 
        ON cd.id = ld.idcabecdoc 
INNER JOIN cabecdocstatus AS cds 
        ON ld.idcabecdoc = cds.idcabecdoc 
WHERE  cd.tipodoc = 'FAR' 
       AND ld.artigo IS NOT NULL 
       AND cds.estado <> 't;r' 
), CTE1 AS
(
SELECT *,ROW_NUMBER() OVER(PARTITION BY Artigo,entidade order by data desc) as RN
FROM CTE
)
SELECT * 
FROM CTE1 
WHERE rn = 1 

可以根据您的确切需求进一步完善代码