获取创建记录时的第一个日期

时间:2012-10-30 07:43:23

标签: sql

我有一个查询,我需要显示首先创建客户信息记录的用户。请参阅下面的查询:

 select CustID, Title, Firstname, Surname, IDNumber, min(ModifyDate) as ModDate, sUsername
from Customers
where StatusCode = 'PI'
group by CustlD,Title,Firstname,Surname,IDNumber,sUsername 

我的结果显示如下:

1    MR    CHARL    8607295    2012-10-23 14:20:31.407   User1
1    MR    CHARL    8607295    2012-10-24 12:36:09.023   User2
2    MISS  XABA     8307297    2012-10-23 14:23:08.593   User1
2    MISS  XABA     8307297    2012-10-24 14:57:29.603   User2

我只需要第一张唱片和第三张唱片。知道我在这里做错了吗?

3 个答案:

答案 0 :(得分:0)

假设您使用的是支持ROW_NUMBER()的数据库系统(现代版本的Oracle,SQL Server,PostgreSQL等):

select CustID, Title, Firstname, Surname, IDNumber, ModifyDate, sUsername
from (
   select
      *,
      ROW_NUMBER() OVER (
          PARTITION BY CustID
          ORDER BY ModifyDate) rn
   from Customers) c
where StatusCode = 'PI' and rn=1

答案 1 :(得分:0)

请改为尝试:

SELECT 
   c1.CustID, 
   c1.Title, 
   c1.Firstname, 
   c1.Surname, 
   c1.IDNumber, 
   c2.ModDate, 
    c1.sUsername
FROM Customers c1
INNER JOIN
(
    SELECT CustID, min(ModifyDate) AS ModDate
    FROM Customers
    GROUP BY CustID
) c2 ON c1.CustID = c2.custID AND c1.ModifyDate = c2.ModDate
WHERE c1.StatusCode = 'PI'

但是,如果您使用的是SQL-Server,则可以使用ROW_NUMBER执行此操作,如@Damien_The_Unbeliever's answer

答案 2 :(得分:0)

select CustID, c1.Title, Firstname, Surname, IDNumber, ModifyDate as ModDate, sUsername
from Customers  c
where StatusCode = 'PI' and c.ModifyDate = (SELECT TOP 1 ModifyDate FROM Customers c_ WHERE c_.CustID = c.CustID ORDER BY ModifyDate ASC)

更新:

select CustID, Firstname, Surname, IDNumber, ModifyDate as ModDate, sUsername
from dbo.test32  c
where c.ModifyDate = (SELECT TOP 1 ModifyDate
                      FROM (
                            SELECT CustID, ModifyDate, CASE WHEN sUserName = 'User1' THEN ROW_NUMBER() OVER (PARTITION BY sUserName ORDER BY ModifyDate ASC) ELSE 2 END AS sn
                            FROM dbo.test32
                            ) c_
                      WHERE c_.sn > 1 AND c_.CustID = c.CustID ORDER BY ModifyDate ASC)