查询客户更改日志以获取最早的记录,以确定创建记录的用户

时间:2017-12-06 17:16:37

标签: sql sql-server

我正在尝试报告哪些用户在我们的客户表中创建了给定记录。不幸的是,它只显示修改记录的最后一个用户。虽然有一个更改日志,所以我需要为给定客户提取最早的记录并提取更改用户的ID。

所以我有这个:

class CenterCellCollectionViewFlowLayout: UICollectionViewFlowLayout {

override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {

    if let cv = self.collectionView {

        let cvBounds = cv.bounds
        let halfWidth = cvBounds.size.width * 0.5;
        let proposedContentOffsetCenterX = proposedContentOffset.x + halfWidth;

        if let attributesForVisibleCells = self.layoutAttributesForElements(in: cvBounds) {

            var candidateAttributes : UICollectionViewLayoutAttributes?
            for attributes in attributesForVisibleCells {

                // == Skip comparison with non-cell items (headers and footers) == //
                if attributes.representedElementCategory != UICollectionElementCategory.cell {
                    continue
                }

                if let candAttrs = candidateAttributes {

                    let a = attributes.center.x - proposedContentOffsetCenterX
                    let b = candAttrs.center.x - proposedContentOffsetCenterX

                    if fabsf(Float(a)) < fabsf(Float(b)) {
                        candidateAttributes = attributes;
                    }

                }
                else { // == First time in the loop == //

                    candidateAttributes = attributes;
                    continue;
                }


            }

            return CGPoint(x : candidateAttributes!.center.x - halfWidth, y : proposedContentOffset.y);

        }

    }

    // Fallback
    return super.targetContentOffset(forProposedContentOffset: proposedContentOffset)
 }
}

但它不会拉动更改用户,因为每个cust_no有多个更改用户。我只需要它来为每个cust_no提取与最早存档日期相关联的更改用户。

思考?

2 个答案:

答案 0 :(得分:1)

执行此操作的规范方法是使用row_number()

SELECT ca.*  
FROM (SELECT ca.*, ROW_NUMBER() OVER (PARTITION BY cust_no ORDER BY archive_date) as seqnum
      FROM mi_masdb.dbo.customer_archive ca 
     ) ca 
WHERE seqnum = 1;

以下可能更快:

select ca.*
from mi_masdb.dbo.customer_archive ca join
     (select ca2.cust_no, min(ca2.archive_date) as min_archive_date
      from mi_masdb.dbo.customer_archive ca2
     ) ca2
     on ca2.cust_no = ca.cust_no and ca2.min_archive_date = ca.archive_date;

答案 1 :(得分:0)

在group by子句中添加change_user列。请参阅下文

SELECT min(ca.archive_date),  
ca.cust_no,  
ca.change_user  
FROM mi_masdb.dbo.customer_archive ca  
GROUP BY ca.cust_no, ca.change_user