获取应该区分的一个字段的记录

时间:2013-04-05 09:27:25

标签: c# asp.net sql sql-server database

我有像

这样的查询
    SELECT distinct(a.CreatedOn),
       a.id AS ID ,
       u1.FirstName CreatedByFirstName,
       u1.LastName
FROM AuditDetail a
LEFT JOIN UserProfile u1 ON a.CreatedBy = u1.UserProfileID
LEFT JOIN UserProfile u2 ON a.UpdatedBy = u2.UserProfileID

这显示了我的所有记录。因为所有记录都在进行,所以在每个记录中也重复了不同的创建。我希望如果所有记录中的createdon相同,那么它的第一条记录或单条记录应该不是全部。哪里我错了?

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用Ranking Function,例如ROW_NUMBER(),为每个群组的每条记录提供排名。

WITH recordList
AS
(
    SELECT  a.CreatedOn,
            a.id as ID ,
            u1.FirstName CreatedByFirstName, 
            u1.LastName,
            ROW_NUMBER() OVER(PARTITION BY a.CreatedOn ORDER BY a.CreatedOn) rn
    FROM    AuditDetail a 
            left join UserProfile u1 
                on a.CreatedBy = u1.UserProfileID 
            left join UserProfile u2 
                on a.UpdatedBy = u2.UserProfileID
)
SELECT  CreatedOn,
        ID,
        CreatedByFirstName,
        LastName
FROM    recordList
WHERE   rn = 1

答案 1 :(得分:1)

试试这个,

可能会帮助你,使用子查询

SELECT a.CreatedOn,
       a.id AS ID ,
       u1.FirstName CreatedByFirstName,
       u1.LastName
FROM AuditDetail a
LEFT JOIN UserProfile u1 ON a.CreatedBy = u1.UserProfileID LEFT joinUserProfileu2 ON a.UpdatedBy = u2.UserProfileID
WHERE a.CreatedOn IN
    (SELECT DISTINCT CreatedOn
     FROM AuditDetail)