sql子查询组由

时间:2011-12-15 22:50:01

标签: sql tsql

我需要一些SQL查询的帮助: 数据如下所示:

ID (int, PK)
REF (int, FK)
UserName (varchar)
TransDate (DateTime)
Status (int)

1, 1001, joebloggs, 2011-12-15 13:50:01, 1
2, 1001, johnsmith, 2011-12-15 14:35:01, 1

所以我需要返回以下的REF和用户名; MIN(TransDate)和status = 1。

所以我做了以下事情:

    SELECT  REF, UserName, MIN(TransDate )
    FROM          dbo.MyTable
    WHERE      (Status = 1)
    and REF = 1001
    GROUP BY REF, UserName

显然这是错误的,因为它让我回答:

1001, joebloggs, 2011-12-15 13:50:01
1001, johnsmith, 2011-12-15 14:35:01

但是,我只需要返回min transDate的用户名。这样:

1001, joebloggs, 2011-12-15 13:50:01

任何人都可以帮助我......让我疯狂。

谢谢(来自我的理智)

5 个答案:

答案 0 :(得分:3)

SELECT REF, UserName, TransDate
FROM dbo.MyTable    
WHERE ID = (
    SELECT TOP 1 ID
    FROM dbo.MyTable
    WHERE Status = 1 AND REF = 1001
    ORDER BY TransDate ASC
)

编辑:

或者,如果您需要每个REF的结果,而不是特定的REF,您可以试试这个:

SELECT mt.REF, mt.UserName, mt.TransDate
FROM 
    dbo.MyTable mt JOIN (
        SELECT
            REF,
            MIN(TransDate) AS MinTransDate
        FROM dbo.MyTable
        WHERE Status = 1
        GROUP BY REF
    ) MinResult mr ON mr.REF = mt.REF AND mr.MinTransDate = mt.TransDate

答案 1 :(得分:2)

这样做怎么样?

SELECT TOP(1) REF, UserName, TransDate
FROM dbo.MyTable
WHERE (Status = 1)
and REF = 1001
ORDER BY TransDate

答案 2 :(得分:0)

尝试

SELECT  REF, UserName, MIN(TransDate )
FROM          dbo.MyTable
WHERE      (Status = 1)
and REF = 1001
and transdate=(select min(transdate) from dbo.MyTable)
GROUP BY REF, UserName;

答案 3 :(得分:0)

几乎就在那里。使用子查询找到min_date,然后连接回原始表以获取其余数据。

select * from dbo.mytable
inner join (select min(transdate)
FROM          dbo.MyTable
WHERE      (Status = 1)
and REF = 1001) a
on mytable.transdate = a.transdate

如果您有多个具有相同trans_date的记录

,此解决方案将返回多行

答案 4 :(得分:-1)

添加order byLimit 1