A表(省略其他字段)
客户号(cid) 状态(tat) 值(val)
12 1 null
13 1 40
B表(省略其他字段)
客户号 状态 值
12 2 30
14 1 50
现在我想 A union B 同时只留一记录为客户号12,根据状态值判断 为2时 将表A的值更新为30
结果为
客户号 状态 值
12 2 30 (这里的其他的字段值为表A的,以表A的值为准)
13 1 40
14 1 50
select语句不会写了,没有思路了,希望各位帮帮忙,谢谢。
------解决方案--------------------
如果只有1、2两种状态就可以用下面的
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-18 17:49:20
-- 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: )
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([cid] int,[tat] int,[val] int)
insert [A]
select 12,1,null union all
select 13,1,40
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go
create table [B]([客户号] int,[状态] int,[值] int)
insert [B]
select 12,2,30 union all
select 14,1,50
--------------开始查询--------------------------
SELECT cid,MAX(tat) tat,MAX( val )val
FROM (
select * from [A]
UNION ALL
select * from [B])a
GROUP BY cid
----------------结果----------------------------
/*
cid tat val
----------- ----------- -----------
12 2 30
13 1 40
14 1 50
*/
------解决方案--------------------
if object_id('[A]') is not null drop table [A]
go
create table [A]([cid] int,[tat] int,[val] int)
insert [A]
select 12,1,null union all
select 13,1,40
if object_id('[B]') is not null drop table [B]
go
create table [B]([cid] int,[tat] int,[val] int)
insert [B]
select 12,2,30 union all
select 14,1,50
go
select distinct a.cid,
case when b.tat = 2
then 2
else a.tat
end as tat,
case when b.tat = 2
then b.val
else a.val
end as val
from A
left join B
on a.cid = b.cid
/*
cid tat val
12 2 30
13 1 40
*/
------解决方案--------------------