过滤表中的选定数据

时间:2016-07-05 14:11:12

标签: sql sql-server sql-server-2008

我尝试仅返回所需的数据,但无法找到仅获取请求数据的方法。我遇到的问题是该表可以有多个相同的记录,但是一列用不同的数据更新。

我想要做的就是获取最新的条目返回代码以及名称和产品的名称,产品和记录数。

同桌:

ID | name | product | ordernum| return code
1    john    abc        14423     0
2    john    abc         14423    1
3    peter   ade        13324     1432
4    peter   abed       43554     1324

所以返回信息看起来应该是这样的。

id | name | product | ordernum | return code | count
2    john    abc       14423          1        2
4    peter   abed      43554       1324        2

关于我如何做到这一点的任何想法?

3 个答案:

答案 0 :(得分:2)

您可以使用窗口功能:

select t.*
from (select t.*,
             row_number() over (partition by name order by id desc) as seqnum,
             count(*) over (partition by name) as cnt
      from t
     ) t
where seqnum = 1;

注意:对于Peter,这将返回4的id;我假设" 2"是一个错字。

答案 1 :(得分:2)

您可以使用ROW_NUMBER()窗口函数来获得结果:

;With Cte As
(
    Select  Id, Name, Product, OrderNum, [Return Code],
            Row_Number() Over (Partition By Name, Product Order By Id Desc) As RN,
            Count(*) Over (Partition By Name, Product) As Count
    From    YourTable
)
Select  Id, Name, Product, OrderNum, [Return Code], Count
From    Cte
Where   RN = 1

答案 2 :(得分:0)

;WITH
cte AS 
(
    SELECT MAX(ID) AS ID, Name, COUNT(Name) OVER(PARTITION BY Name) AS [COUNT]
    FROM Table
    GROUP BY Name
)
SELECT * 
FROM Table a
JOIN cte b
    ON a.ID = b.ID
    AND a.Name = b.Name