2

我有一个包含两列的表,ID 和描述。当 ID = 1 时,描述代表人的姓名。当 ID = 2 时,描述表示此人的地址。ID 为 3 时,描述代表该人的评论。

我必须执行什么查询才能选择所有三种类型的描述。我尝试使用案例,但这不适用于我的案例。Union 将起作用,但我将运行我的查询三遍。有没有更简单有效的方法来做到这一点?

4

3 回答 3

1

我猜你有办法将这些数据与另一个表相关联。如果是这样,那么你可以使用这样的东西:

select t1.someId,
    max(case when t2.id = 1 then t2.description end) name,
    max(case when t2.id = 2 then t2.description end) address,
    max(case when t2.id = 3 then t2.description end) comments
from table1 t1
left join table2 t2
    on t1.someId = t2.someid
group by t1.someId

这将为您提供特定行中每条记录的唯一数据。然后,您可以将此数据插入到另一个表中。

于 2012-10-15T14:46:39.910 回答
1

这是一个非常糟糕的方法,但可以通过以下方式解决:(我在表中添加了一个 personID 作为它的主键)

create table person(
personID int,
id int,
description varchar(40))

insert into person values (1,1, 'name')
insert into person values (1,2, 'adress')
insert into person values (1,3, 'comments')



SELECT p.personID, p.description, p2.description, p3.description
FROM person p JOIN person p2 ON p.personID=p2.personID and  p.id=1 and p2.id=2 JOIN person p3 ON p.personID=p3.personID AND p3.ID=3
于 2012-10-15T14:56:07.350 回答
0

这就是解决方案。感谢所有提供任何反馈的人。

select table.ID,
max (case when id = 1 then description end) as size
max (case when id = 2 then description end) as address
max (case when id = 3 then description end) as comments
group by id
于 2012-10-15T14:59:33.230 回答