我正在使用以下查询从子组中具有最小日期差异的那些中提取随机行(由ID1,ID2对定义)。
它不起作用,因为按日期差异对行进行排名的步骤仅将rank = 1分配给第一个观察(即,即使第二个具有相同的日期差异并且也应该接收等级= 1)。
不知何故,我需要将WHEN子句更改为......
CASE
WHEN @id1 = t.id1 AND @id2 = t.id2 AND @diff != diff THEN @rownum := @rownum + 1
ELSE @rownum := 1
但是当我这样做时,它找不到差异字段......
DROP TABLE IF EXISTS temp4;
CREATE TABLE temp4 AS
SELECT x.id1,
x.id2,
x.YEAR,
x.MMDD,
x.id3,
x.id3_YEAR,
x.id3_MMDD,
x.rk
FROM (SELECT t.*,
ABS(DATEDIFF(CONCAT(CAST(t.id3_YEAR AS CHAR(4)),'-', LEFT(t.id3_MMDD,2),'-',RIGHT(t.id3_MMDD,2)),
CONCAT(CAST(t.YEAR AS CHAR(4)),'-', LEFT(t.MMDD,2),'-',RIGHT(t.MMDD,2)))) AS diff,
CASE
WHEN @id1 = t.id1 AND @id2 = t.id2 THEN @rownum := @rownum + 1
ELSE @rownum := 1
END AS rk,
@id1 := t.id1,
@id2 := t.id2
FROM temp3 t
JOIN (SELECT @rownum := 0, @id1 := 0, @id2 := 0) r
ORDER BY t.id1, t.id2, diff, RAND()) x;
我正在粘贴SQL转储
DROP TABLE IF EXISTS `temp3`;
CREATE TABLE IF NOT EXISTS `temp3` (
`id1` char(7) NOT NULL,
`id2` char(7) NOT NULL,
`YEAR` year(4) NOT NULL,
`MMDD` char(4) NOT NULL,
`id3` char(7) NOT NULL,
`id3_YEAR` year(4) NOT NULL,
`id3_MMDD` char(4) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `temp3` VALUES('1', '2', 1992, '0107', '55', 1991, '0528');
INSERT INTO `temp3` VALUES('1', '2', 1992, '0107', '57', 1991, '0701');
INSERT INTO `temp3` VALUES('1', '3', 1992, '0107', '88', 2000, '0101');
INSERT INTO `temp3` VALUES('1', '3', 1992, '0107', '44', 2000, '0101');
这个版本实际上非常接近我的需要
DROP TABLE IF EXISTS temp4;
CREATE TABLE temp4 AS
SELECT
x.id1,
x.id2,
x.YEAR,
x.MMDD,
x.id3,
x.id3_YEAR,
x.id3_MMDD
FROM
( SELECT
t.*,
@rownum := CASE
WHEN @id1 = t.id1 AND @id2 = t.id2 AND @diff != diff THEN @rownum + 1
ELSE 1
END AS rk,
@id1 := t.id1,
@id2 := t.id2,
@diff := t.diff
FROM
( SELECT
t.*,
ABS(DATEDIFF(CONCAT(CAST(t.id3_YEAR AS CHAR(4)),'-', LEFT(t.id3_MMDD,2),'-',RIGHT(t.id3_MMDD,2)),
CONCAT(CAST(t.YEAR AS CHAR(4)),'-', LEFT(t.MMDD,2),'-',RIGHT(t.MMDD,2)))) AS diff
FROM temp3 t
ORDER BY t.id1, t.id2, diff, RAND()
) t,
( SELECT @rownum := 0, @id1 := null, @id2 := null, @diff := null ) r
) x
WHERE x.rk = 1;
答案 0 :(得分:0)
这是一个有效的解决方案。谢谢@OMG小马的帮助。
SELECT
x.id1,
x.id2,
x.YEAR,
x.MMDD,
x.id3,
x.id3_YEAR,
x.id3_MMDD
FROM
( SELECT
t.*,
@rownum := CASE
WHEN @id1 = t.id1 AND @id2 = t.id2 THEN @rownum + 1
ELSE 1
END AS rk,
@id1 := t.id1,
@id2 := t.id2
FROM
( SELECT
t.*,
ABS(DATEDIFF(CONCAT(CAST(t.id3_YEAR AS CHAR(4)),'-', LEFT(t.id3_MMDD,2),'-',RIGHT(t.id3_MMDD,2)),
CONCAT(CAST(t.YEAR AS CHAR(4)),'-', LEFT(t.MMDD,2),'-',RIGHT(t.MMDD,2)))) AS diff
FROM temp3 t
ORDER BY t.id1, t.id2, diff, RAND()
) t,
( SELECT @rownum := 0, @id1 := null, @id2 := null ) r
) x
WHERE x.rk = 1;