读书人

查询时直接去掉结果集里的重复

发布时间: 2014-04-23 16:19:42 作者: rapoo

查询时直接去除结果集里的重复。
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
/*
cidtatval
12230
13140
*/

[解决办法]
引用:
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语句不会写了,没有思路了,希望各位帮帮忙,谢谢。



如果B表中会不会存在一条记录 是 13 2 50
如果这样,楼主要查询的结果是..?
[解决办法]
--> 测试数据:[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](cid int,[tat] int,[val] int)
insert [B]
select 12,2,30 union all
select 14,1,50
--------------开始查询--------------------------

select ISNULL(a.cid,b.cid)cid,CASE WHEN a.tat IS NOT NULL AND b.tat IS NOT NULL THEN 3 ELSE ISNULL(a.tat,b.tat) END tat,ISNULL(a.val,b.val)val
from [A] full JOIN [B]ON a.cid=b.cid
/*
cid tat val
----------- ----------- -----------
12 3 30
13 1 40
14 1 50

*/

[解决办法]
引用:
Quote: 引用:

所以我要问你具体规则,单从你的例子中是可以的....你的响应时间也太长了吧

是啊,抱歉我问问题的技巧有待提高。状态值有1,2,3。1表示一种情况,2表示一种情况,3表示两种情况都有。表A只会有状态1,表B只会有状态2,当两个表出现同一客户,更新成状态3,剩下的字段的值以表A为准。


楼主, 我7楼的写法能够查询出来哦

读书人网 >SQL Server

热点推荐