首次查询状态更改

时间:2012-09-07 09:49:53

标签: mysql sql database data-modeling

我有一张如下表格

      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的状态从17变为1本身。

2 个答案:

答案 0 :(得分: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 )

答案 1 :(得分:0)

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