求一条SQL 语句。该如何处理
求一条SQL 语句。
有两张表:
求这样的SQL语句该如何写?谢谢。
------解决方案--------------------
------解决方案--------------------
试试这个:
有两张表:
table1:
A B
1 4
2 5
3 6
tabel2:
C STATUS
8 null
9 有数据
10 null
我现在想用一条SQL语句,把表2(table2)里面的status字段值为空(null)的数据叠加到表1(table1)的数据里面,字段C放到字段A里面去,得到的结果像下面的效果:
A B STATUS
1 4 NULL
2 5 NULL
3 6 NULL
8 NULL NULL
10 NULL NULL
求这样的SQL语句该如何写?谢谢。
------解决方案--------------------
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-01-24 12:57:57
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[table1]
if object_id('[table1]') is not null drop table [table1]
go
create table [table1]([A] int,[B] int)
insert [table1]
select 1,4 union all
select 2,5 union all
select 3,6
--> 测试数据:[tabel2]
if object_id('[tabel2]') is not null drop table [tabel2]
go
create table [tabel2]([C] int,[STATUS] varchar(6))
insert [tabel2]
select 8,null union all
select 9,'有数据' union all
select 10,null
--------------开始查询--------------------------
select * ,NULL [STATUS]
from [table1]
UNION ALL
select C ,NULL,[STATUS] from [tabel2]
WHERE [STATUS] IS NULL
----------------结果----------------------------
/*
A B STATUS
----------- ----------- ------
1 4 NULL
2 5 NULL
3 6 NULL
8 NULL NULL
10 NULL NULL
*/
------解决方案--------------------
试试这个:
--drop table table1,table2
--go
create table table1(A int, B int)
insert into table1
select 1 , 4 union all
select 2 , 5 union all
select 3 , 6
create table table2(C int, STATUS varchar(20))
insert into table2
select 8 , null union all
select 9 , '有数据' union all
select 10 , null
go
select A,b,null status from table1
union all
select C,null,STATUS from table2 where STATUS is null
/*
A b status
1 4 NULL
2 5 NULL
3 6 NULL
8 NULL NULL
10 NULL NULL
*/