SQL查询返回与列的所有值对应的数据,但该列的最小值除外

时间:2013-09-11 08:59:59

标签: sql sql-server datetime

我有一个包含以下列的表:

userid, datetime, type

示例数据:

userid  datetime               type
   1    2013-08-01 08:10:00     I
   1    2013-08-01 08:12:00     I 
   1    2013-08-01 08:12:56     I

我需要获取除min(datetime)

行之外的两行数据

我获取min(datetime)数据的查询是:

SELECT  
    USERID, MIN(CHECKTIME) as ChkTime, CHECKTYPE, COUNT(*) AS CountRows
FROM
    T1
WHERE 
    MONTH(CONVERT(DATETIME, CHECKTIME)) = MONTH(DATEADD(MONTH, -1,
CONVERT(DATE, GETDATE())))
    AND YEAR(CONVERT(DATETIME, CHECKTIME)) = YEAR(GETDATE()) AND USERID=35
    AND CHECKTYPE='I'
GROUP BY 
    CONVERT(DATE, CHECKTIME), USERID, CHECKTYPE 
HAVING 
    COUNT(*) > 1 

一个小小的帮助将非常感谢..thnx

2 个答案:

答案 0 :(得分:1)

也许这样的事情可以帮到你:

WITH CTE AS 
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY userid ORDER BY checktime) RN
    FROM dbo.T1
    WHERE CHECKTYPE = 'I' 
    --add your conditions here
)
SELECT * FROM CTE
WHERE RN > 1

使用CTEROW_NUMBER()功能,这将为每个用户选择除min(日期)以外的所有行。

<强> SQLFiddle DEMO

答案 1 :(得分:0)

SELECT * FROM YOURTABLE A
INNER JOIN
(SELECT USERID,TYPE,MIN(datetime) datetime FROM YOURTABLE GROUP BY  USERID,TYPE )B
ON
A.USERID=B.USERID AND
A.TYPE=B.TYPE 
WHERE A.DATETIME<>B.DATETIME