我有一张包含gr_no,year_dob,family_id等的表格。 我试图根据family_id对出生年份进行排名,但无法生成siblings_rank结果。
+----------+--------------+-----------+
| gr_no | year_dob | family_id | siblings_rank
+----------+--------------+-----------+
| 1001 | 1992 | 95 | 1
| 10234 | 1995 | 95 | 2
| 10236 | 2004 | 96 | 1
| 15568 | 2006 | 96 | 2
| 1225 | 2004 | 92 | 1
+----------+--------------+-----------+
此查询有效:
SET @prev := null;
SET @cnt := 1;
SELECT gr_no, gs_id, gf_id, year_dob, IF(@prev <> gf_id, @cnt := 1, @cnt := @cnt + 1) AS siblings_position, @prev := gf_id as previous_gf_id
FROM student_registered
ORDER BY gf_id, year_dob asc
此查询也有效:
SELECT gr_no, gs_id, gf_id, year_dob, IF(@prev <> gf_id, @cnt := 1, @cnt := @cnt + 1) AS siblings_position, @prev := gf_id as previous_gf_id
FROM student_registered
JOIN (SELECT @prev := null) p
JOIN (SELECT @cnt := 1) c
ORDER BY gf_id, year_dob asc
...............我无法使用这些查询创建视图?
或 如果一个过程可以根据查询更新student_registered列'siblings_position'吗?
答案 0 :(得分:0)
你不能在视图中使用sql变量
这是使用相关子查询
获得相同结果的另一种方法SELECT gr_no, family_id,year_dob,
( select count(*) from Table1 T1
where T1.family_id = T.family_id
and T1.year_dob <= T.year_dob) as siblings_position
FROM Table1 T
ORDER BY family_id, year_dob asc