2012-09-07 50 views
1

我有一个表像下面查询的状态改变第一次

 
     CREATE TABLE Customers_History(Row_Id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
          Cust_Name VARCHAR(255), 
          Created_Date DATE, 
          Cust_Status TINYINT) 

在表中的行下面

 

INSERT INTO Customers_History(Cust_Name, Created_Date, Cust_Status) 
        VALUES('Customer A', '20120516', 0), 
          ('Customer B', '20120516', 0), 
          ('Customer C', '20120516', 0), 

          ('Customer A', '20120517', 1), 
          ('Customer B', '20120517', 0), 
          ('Customer C', '20120517', 0), 

          ('Customer A', '20120520', 1), 
          ('Customer B', '20120520', 0), 
          ('Customer C', '20120520', 1), 

          ('Customer A', '20120521', 0), 
          ('Customer B', '20120521', 0), 
          ('Customer C', '20120521', 1), 

          ('Customer A', '20120526', 1), 
          ('Customer B', '20120526', 1),     
          ('Customer C', '20120526', 0); 

我想要的,采取日期参数如下使输出查询

当我通过20120517作为日期参数的类别时,它应该使客户A的状态从0变为1

 
    Customer A 

当我通过20120520作为参数的日期在类应该带来顾客C作为其状态从0改变为1

 
    Customer C 

当我通过20120526如在类应该带来参数为日客户B的状态从0变为1

 
    Customer B 

我想要第一次将状态从0改为1的特定日期的客户名称。

注意:当我通过20120526作为日期参数的类别时,它不应该将客户A带到客户A,因为客户A状态从17自身从0更改为1。

+0

的表我会希​​望只包含独特的客户,而不是一个数量每个客户的陈述。而是创建一个单独的CustomerStates表,其中包含这些数据并通过CustomerID链接到Customers。 – GolezTrol

+0

我正在跟踪此表中的客户历史记录。如果我按照您所述创建了单独的表格,那么我如何跟踪该客户的状态 – user1093513

+0

然后将其命名为CustomerHistory。当前表格显示它是包含实际客户的客户表。 – GolezTrol

回答

2

你去那里:名为“客户”

select 
    c.Cust_Name 
from 
    Customers_History c 
where 
    c.CreatedDate = :YourDate and 
    c.Cust_Status = 1 and 
    not exists 
    (select 
     'x' 
     from 
     Customers_History c2 
     where 
     c2.Cust_Name = c.CustName and 
     c2.Cust_Status = 1 and 
     c2.Created_Date < c.Created_Date) 
+0

工作像魅力感谢一吨。我希望你不会介意,如果我问你上述要求的适当的表设计。预先感谢 – user1093513

0
select Cust_Name from customers_history where Created_Date='2012-05-17' and 
Cust_Status=1 order by Cust_Name desc limit 1 
+0

你还没有理解我的问题 – user1093513