两张构造一样的表,选出当前表记录数大于备份表的记录
两张结构一样的表,选出当前表记录数大于备份表的记录
两张结构一样的表,一张当前表Current,一张备份表Bak
Bak字段,值如下
id name
1000 N1
1001 N2
1002 N3
Current字段,值如下
id name
1000 N1
1000 N9
1001 N2
1002 N3
1002 N4
1002 N5
我想用一条SQL语句,将当前表Current 中 group by id 后, 如果记录数大于 bak 中相同的记录的记录数,select 出来
因为 Current表 id=1000 的记录数为2 > Bak表 id=1000 的记录数为1 故select出来
因为 Current表 id=1002 的记录数为3 > Bak表 id=1000 的记录数为1 故select出来
------解决方案--------------------
两张结构一样的表,一张当前表Current,一张备份表Bak
Bak字段,值如下
id name
1000 N1
1001 N2
1002 N3
Current字段,值如下
id name
1000 N1
1000 N9
1001 N2
1002 N3
1002 N4
1002 N5
我想用一条SQL语句,将当前表Current 中 group by id 后, 如果记录数大于 bak 中相同的记录的记录数,select 出来
因为 Current表 id=1000 的记录数为2 > Bak表 id=1000 的记录数为1 故select出来
因为 Current表 id=1002 的记录数为3 > Bak表 id=1000 的记录数为1 故select出来
------解决方案--------------------
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2014-03-10 16:49:04
-- Verstion:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[Bak]
if object_id('[Bak]') is not null drop table [Bak]
go
create table [Bak]([id] int,[name] varchar(2))
insert [Bak]
select 1000,'N1' union all
select 1001,'N2' union all
select 1002,'N3'
--> 测试数据:[Current]
if object_id('[Current]') is not null drop table [Current]
go
create table [Current]([id] int,[name] varchar(2))
insert [Current]
select 1000,'N1' union all
select 1000,'N9' union all
select 1001,'N2' union all
select 1002,'N3' union all
select 1002,'N4' union all
select 1002,'N5'
--------------开始查询--------------------------
select
a.id
from
(select id,count(1) as num from bak group by id) as a
inner join
(select id,count(1) as num from [Current] group by id) as b
on
a.id=b.id
and
b.num>a.num
----------------结果----------------------------
/* id
-----------
1000
1002
(2 行受影响)
*/