1

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

 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

我只需要第一条记录和第三条记录。知道我在这里做错了什么吗?

4

3 回答 3

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
于 2012-10-30T07:54:15.050 回答
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,那么您可以使用@Damien_The_Unbeliever 的答案ROW_NUMBER来执行此操作。

于 2012-10-30T07:55:44.833 回答
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)
于 2012-10-30T13:48:34.293 回答