0
如果这是重复的,我不会感到惊讶,但我一直未能在主题上找到这种变体。将枚举类型和相应的值转换为SQL中的单独列
我有一个表有两列:一个表示数据类型,另一个表示相应的值。我想使用SELECT进行转换,以便每个枚举的“类型”是它自己的列由值填充。
Table PersonInfo
InfoID PersonID AttributeType AttributeValue
1 1 email [email protected]
2 1 dept research
3 2 email [email protected]
4 2 dept engineering
5 3 email [email protected]
SELECT结果将是:
PersonID email dept
1 [email protected] research
2 [email protected] engineering
3 [email protected] NULL
正如你所看到的,INFOID指数不再需要。
在我的情况下,我知道AttributeType列中的潜在值,所以我不需要它是完全动态的。
这里是我的尝试:
SELECT DISTINCT PersonID,
CASE AttributeType WHEN 'email' THEN AttributeValue ELSE null END as email
CASE AttributeType WHEN 'dept' THEN AttributeValue ELSE null END as dept
我知道这是为什么失败了,但我不知道该怎么做才能得到它的工作,因为我想。
另一种方法是将电子邮件和部门分为不同的列。一个用于多个目的的列通常很难处理。感谢您可能无法更改数据库设计。 –
这个答案:http://stackoverflow.com/questions/16916470/convert-row-value-in-to-column-in-sql-server-pivot似乎正是我想要的。 –