zoukankan      html  css  js  c++  java
  • SQL查询所有用户最后一天的数据

    CREATE TABLE UserLog
    (
        UserId INT NOT NULL,
        UpdateDate DATETIME NOT NULL DEFAULT GETDATE(),
        [Action] VARCHAR(300) NOT NULL
    )
    GO
    INSERT INTO UserLog(UserId,[Action])VALUES(1,'开始')
    INSERT INTO UserLog(UserId,[Action])VALUES(1,'麦仁')
    INSERT INTO UserLog(UserId,[Action])VALUES(1,'理事')
    INSERT INTO UserLog(UserId,[Action])VALUES(1,'结束')
    INSERT INTO UserLog(UserId,[Action])VALUES(2,'开始')
    INSERT INTO UserLog(UserId,[Action])VALUES(2,'麦仁')
    INSERT INTO UserLog(UserId,[Action])VALUES(3,'理事')
    INSERT INTO UserLog(UserId,[Action])VALUES(4,'结束')
    
    INSERT INTO UserLog(UserId,UpdateDate,[Action])VALUES(1,DATEADD(hh,-99,GETDATE()),'开始')
    INSERT INTO UserLog(UserId,UpdateDate,[Action])VALUES(1,DATEADD(hh,-98,GETDATE()),'麦仁')
    INSERT INTO UserLog(UserId,UpdateDate,[Action])VALUES(1,DATEADD(hh,-97,GETDATE()),'理事')
    INSERT INTO UserLog(UserId,UpdateDate,[Action])VALUES(1,DATEADD(hh,-96,GETDATE()),'结束')
    INSERT INTO UserLog(UserId,UpdateDate,[Action])VALUES(2,DATEADD(hh,-95,GETDATE()),'开始')
    INSERT INTO UserLog(UserId,UpdateDate,[Action])VALUES(2,DATEADD(hh,-94,GETDATE()),'麦仁')
    INSERT INTO UserLog(UserId,UpdateDate,[Action])VALUES(3,DATEADD(hh,-93,GETDATE()),'理事')
    INSERT INTO UserLog(UserId,UpdateDate,[Action])VALUES(4,DATEADD(hh,-92,GETDATE()),'结束')
    GO
    SELECT * FROM UserLog ul
    GO
    --显示数据如下:

    --第一步 根据用户分组 取日期最大值
    WITH L AS 
    (
        SELECT ul.UserId,convert(varchar(10),MAX(ul.UpdateDate),120) UpdateDate FROM UserLog ul GROUP BY ul.UserId
    )
    --第二步 左外连接 主表 匹配 用户和日期
    SELECT ul.* FROM L l LEFT JOIN UserLog ul 
    ON l.UserId = ul.UserId AND CONVERT(VARCHAR(10),ul.UpdateDate,120) = l.UpdateDate
    GO
    --显示数据如下:

    OK 想要的数据就这样查询出来了。

  • 相关阅读:
    参考文献怎么写~(这个老是忘,所以贴在这里)
    STL 容器之 priority_queue小结
    新闻发布系统-项目总结
    【DataStructure In Python】Python模拟二叉树
    【HDOJ】2062 Subset sequence
    【POJ】1054 The Troublesome Frog
    【Pyhton Network】使用poll()或select()实现非阻塞传输
    【Python Network】分解DNS查询结果
    【DataStructure In Python】Python实现各种排序算法
    【Python Network】权威域名服务器级联查询
  • 原文地址:https://www.cnblogs.com/ziqixing/p/2917409.html
Copyright © 2011-2022 走看看