求一SQL语句

ye7813629 2012-05-16 11:04:06
表一Building
字段ID,Name,BuildingState,UseType等。。。
BuildingState,UseType为整数类型
表二CODEVALUE
字段 CodeType,CodeID,CodeValue
表二的值是指定的,比如CodeType=BuildingState,CodeID=0,CodeValue=在建建筑物
CodeType=BuildingUseType,CodeID=0,CodeValue=商业用途
现在要查询表一的信息,返回的BuildingState和UseType不是0或1什么的,假如BuildingState查出来为0,则对应CODEVALUE下面的CodeType为BuildingState并且CodeID=0返回的CodeValue。
...全文
81 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复

--> 测试数据:[Building]
if object_id('[Building]') is not null drop table [Building]
create table [Building]([ID] int,[Name] varchar(10),[BuildingState] int,[UseType] int)
insert [Building]
select 1,'xx花园xx栋',0,1 union all
select 2,'xx花园xx栋',1,1
--> 测试数据:[CODEVALUE]
if object_id('[CODEVALUE]') is not null drop table [CODEVALUE]
create table [CODEVALUE]([CodeType] varchar(15),[CodeID] int,[CodeValue] varchar(12))
insert [CODEVALUE]
select 'BuildingState',0,'在建建筑物' union all
select 'BuildingState',1,'已竣工建筑物' union all
select 'BuildingUseType',0,'商业用途' union all
select 'BuildingUseType',1,'住宅用途'


select t.ID,t.Name,t.CodeValue as BuildingState,
d.CodeValue as BuildingUseType from(
select a.ID,a.Name,b.CodeValue,a.UseType from [Building] a
inner join [CODEVALUE] b on a.BuildingState=b.CodeID
where b.CodeType='BuildingState')t
inner join [CODEVALUE] d
on t.UseType=d.CodeID
where d.CodeType='BuildingUseType'

/*

ID Name BuildingState BuildingUseType
1 xx花园xx栋 在建建筑物 住宅用途
2 xx花园xx栋 已竣工建筑物 住宅用途
*/
ye7813629 2012-05-16
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

SQL code
select
case when a.BuildingState=0 and b.CodeType='BuildingState' and b.CodeID=0 then b.CodeValue else 0 end ,
case when a.UseType=1 and b.CodeType='BuildingState' and b.CodeID=0 then……
[/Quote]
数据假如是:Building表
ID,Name,BuildingState,UseType
1,xx花园xx栋,0,1
2,xx花园xx栋,1,1
CODEVALUE表
CodeType, CodeID, CodeValue
BuildingState 0 在建建筑物
BuildingState 1 已竣工建筑物
BuildingUseType 0 商业用途
BuildingUseType 1 住宅用途

单查一个表,会的到
1,xx花园xx栋,0,1
2,xx花园xx栋,1,1

但是我希望得当的是
1,xx花园xx栋,在建建筑物,住宅用途
1,xx花园xx栋,已竣工建筑物,住宅用途
ye7813629 2012-05-16
  • 打赏
  • 举报
回复
数据假如是:Building表
ID,Name,BuildingState,UseType
1,xx花园xx栋,0,0
CODEVALUE表
CodeType, CodeID, CodeValue
BuildingState 0 在建建筑物
BuildingState 1 已竣工建筑物
BuildingUseType 0 商业用途
BuildingUseType 1 住宅用途

单查一个表,会的到 1,xx花园xx栋,0,1 这个数据

但是我希望得当的是
1,xx花园xx栋,在建建筑物,住宅用途
--小F-- 2012-05-16
  • 打赏
  • 举报
回复
select
case when a.BuildingState=0 and b.CodeType='BuildingState' and b.CodeID=0 then b.CodeValue else 0 end ,
case when a.UseType=1 and b.CodeType='BuildingState' and b.CodeID=0 then b.CodeValue else 0 end
from
Building a inner join CODEVALUE b
on
a.xx=b.xx


纯粹的猜测。
  • 打赏
  • 举报
回复
测试数据额。这个看得头晕
孤独加百列 2012-05-16
  • 打赏
  • 举报
回复
给测试数据和希望结果

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧