日期:2014-05-17  浏览次数:20538 次

SQLServer2005在同一列中如何显示来自多表的信息
表A
DATE           DB        DH            XH
-------------------------------------------------
2012-10-5      591       121000020     0012
2012-10-12     541       121000151     0002
2012-11-05     D31       121100025     0030 

表B
DB       DH             XH         NOTE
-------------------------------------------------
591     121000020      0012       俄罗斯7362 

表C
DB       DH          XH         NOTE
-------------------------------------------------
541    121000151     0002      奥大利亚007157 

表D
DB       DH           XH        NOTE
-------------------------------------------------
D31     121100025    0030       佛山专卖 

现在要查询A、B、C、D四个表的信息,结果如以下显示:
DATE           DB      DH           XH       NOTE
----------------------
2012-10-5      591    121000020    0012     俄罗斯7362
2012-10-12     541    121000151    0002     奥大利亚007157
2012-11-05     D31    121100025    0030     佛山专卖    

SQL语句该怎么写呢?用CASE WHEN能做到吗?还望高手说得详细些,谢谢!
------最佳解决方案--------------------
1:日期格式出现很多0,是因为你定义的字段类型是datetime,而添加数据时只给了date,如果不想显示时间,最好定义为Date类型
2:出现这么多重复的数据,你在BCD表中添加了重复的数据,最后表有主键约束,或唯一性约束
3:过滤重复的数据,可以用distinct
如下,我试过了,是可以的:

select distinct E.DATE,E.DB,E.DH,E.XH,(
case 
when E.BNote is not null then E.BNote
when E.Cnote is not null then E.Cnote
when E.Dnote is not null then E.Dnote
else null
end ) as Note
from 
(select A.DATE,A.DB,A.DH,A.XH,B.NOTE BNote,C.NOTE Cnote,D.NOTE Dnote from tableA A
left join tableB B on A.DB =B.DB
left join tableC C on A.DB =C.DB
left join tableB D on A.DB =D.DB) as E

------其他解决方案--------------------

--表A
if OBJECT_ID('tableA') is not null
drop table tableA