以下是表格:抱歉无法在这里正确描述表格。
Id Date1 Rank1 date2 Rank2
100 1/1/01 1 1/2/01 1
100 1/2/01 1 1/3/01 1
100 1/3/01 1 1/5/01 4
现在,我希望看到排名发生变化的结果,但是date1应该显示Rank = 1开始的日期, 像这样的输出:
Id Date1 Rank1 date2 Rank2
100 1/1/01 1 1/5/01 4
任何人都可以让我知道如何在MYSQL中这样做吗?我想过使用SQL游标。还有其他方法吗?
答案 0 :(得分:1)
我将创建一个存储过程和一个游标来迭代每条记录。
我的存储过程如下所示:
CREATE PROCEDURE `GetChangedRank`()
BEGIN
# Variables containing the final result
DECLARE ID INTEGER;
DECLARE DATE1 DATE;
DECLARE Rank1 INTEGER;
DECLARE DATE2 DATE;
DECLARE Rank2 INTEGER;
DECLARE ROWNUM INTEGER DEFAULT 0;
# Temporary variables to store values of each row.
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE ID_VALUE INT;
DECLARE DATE1_VALUE DATE;
DECLARE Rank1_VALUE INT;
DECLARE DATE2_VALUE DATE;
DECLARE Rank2_VALUE INT;
# testtable is the table that contains data
DECLARE RECORDS_CURSOR CURSOR FOR SELECT * FROM testtable;
# To check if we reached the end of the result set
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
# Open cursor
OPEN RECORDS_CURSOR;
# Loop to fetch one row at a time
get_records: LOOP
# Fetch row values to different variables
FETCH RECORDS_CURSOR INTO ID_VALUE, DATE1_VALUE, Rank1_VALUE, DATE2_VALUE, Rank2_VALUE
# To track the row number
SET ROWNUM = ROWNUM + 1;
# Quit the loop when the end of resultset is reached.
IF v_finished = 1 THEN
LEAVE get_records;
END IF;
# Assign the first row values to the final values. Date2 and Rank2 will be updated when the rank is changed.
IF ROWNUM = 1 THEN
BEGIN
SET ID = ID_VALUE;
SET DATE1 = DATE1_VALUE;
SET Rank1 = Rank1_VALUE;
SET DATE2 = DATE2_VALUE;
SET Rank2 = Rank2_VALUE;
END;
ELSE
BEGIN
# Date2 and Rank2 is updated with the row values as the rank is changed.
IF Rank1_VALUE != Rank2_VALUE THEN
BEGIN
SET DATE2 =DATE2_VALUE;
SET Rank2 = Rank2_VALUE;
END;
END IF;
END;
END IF;
END LOOP get_records;
# Select the final values
SELECT ID, DATE1, Rank1, DATE2, Rank2;
# Close cursor
CLOSE RECORDS_CURSOR;
END
创建过程后,您可以按照以下步骤运行此过程
CALL GetChangedRank;
答案 1 :(得分:0)
这是你想要的吗?
SELECT * FROM <table name>
WHERE Rank1 <> Rank2
答案 2 :(得分:0)
尝试此嵌套查询
Select Id, (select Date1 from TableName group by Rank1) as Date1, Rank1, Date2, Rank2 from TableName where Rank1<>Rank2;