根据另一列中的不同值设置列值

时间:2012-12-29 14:20:39

标签: sql distinct inner-join

我正在尝试做一些与此问题非常相似的事情:mysql - UPDATEing row based on other rows

我有一个名为modset的表,格式如下:

member    year    y1    y2    y3    y1y2    y2y3    y1y3    y1y2y3 
a         1       0     0     0     0       0       0       0
a         2       0     0     0     0       0       0       0
a         3       0     0     0     0       0       0       0
b         1       0     0     0     0       0       0       0
b         2       0     0     0     0       0       0       0
c         1       0     0     0     0       0       0       0
c         3       0     0     0     0       0       0       0
d         2       0     0     0     0       0       0       0

第3:9列是二进制标志,用于指示成员记录的年份组合。所以我希望SQL更新的结果如下所示:

member    year    y1    y2    y3    y1y2    y2y3    y1y3    y1y2y3 
a         1       0     0     0     0       0       0       1
a         2       0     0     0     0       0       0       1
a         3       0     0     0     0       0       0       1
b         1       0     0     0     1       0       0       0
b         2       0     0     0     1       0       0       0
c         1       0     0     0     0       0       1       0
c         3       0     0     0     0       0       1       0
d         2       0     1     0     0       0       0       0

上面链接的问题中的代码非常接近,但只有当它是成员记录的不同年份的计数时。我需要根据成员记录的年份的特定值来建立列。

提前致谢!

SELECT member,
    case when min(distinct(year)) = 1 and max(distinct(year)) = 1 then 1 else 0 end y1,
    case when min(distinct(year)) = 1 and max(distinct(year)) = 2 then 1 else 0 end y1y2,
    case when min(distinct(year)) = 1 and max(distinct(year)) = 3 and count(distinct(year)) = 2 then 1 else 0 end y1y3,
    case when min(distinct(year)) = 1 and max(distinct(year)) = 3 and count(distinct(year)) = 3 then 1 else 0 end y1y2y3,
    case when min(distinct(year)) = 2 and max(distinct(year)) = 2 then 1 else 0 end y2,
    case when min(distinct(year)) = 2 and max(distinct(year)) = 3 then 1 else 0 end y2y3,
    case when min(distinct(year)) = 3 then 1 else 0 end y3
INTO temp5
FROM modset
GROUP BY member;

UPDATE modset M
SET y1 = T.y1, y2 = T.y1, y3 = T.y3, y1y2 = T.y1y2, y1y3 = T.y1y3, y2y3 = T.y2y3, y1y2y3 = T.y1y2y3
FROM temp5 T
WHERE T.member = M.member;

1 个答案:

答案 0 :(得分:2)

您使用什么查询来返回会员记录年份的指标?

听起来您需要获取查询结果并在更新中使用它:

http://dev.mysql.com/doc/refman/5.0/en/update.html

看起来像这样:

UPDATE targetTable t, sourceTable s 
SET t.y1 = s.y1, t.y2 = s.y2 -- (and so on...)
WHERE t.member = s.member AND t.year = m.year;