日期:2014-05-16 浏览次数:21234 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-02-11 08:07: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: )
--
----------------------------------------------------------------
--> 测试数据:[table1]
if object_id('[table1]') is not null drop table [table1]
go
create table [table1]([id] int,[name1] varchar(3))
insert [table1]
select 1,'123' union all
select 2,'456' union all
select 3,'789' union all
select 4,'012'
--> 测试数据:[table2]
if object_id('[table2]') is not null drop table [table2]
go
create table [table2]([id] int,[name2] varchar(3))
insert [table2]
select 1,'098' union all
select 2,'123' union all
select 3,'789' union all
select 4,'123'
--------------开始查询--------------------------
IF exists (
SELECT ROW_NUMBER()OVER(ORDER BY name2 )id , name2 AS NAME,table1,table2
FROM (SELECT name2,COUNT(1) 'table2' FROM table2 GROUP BY name2) a
INNER JOIN (SELECT name1,COUNT(1) 'table1' FROM [table1] GROUP BY name1) b ON a.name2=b.name1)
SELECT ROW_NUMBER()OVER(ORDER BY name2 )id , name2 AS NAME,table1,table2
FROM (SELECT name2,COUNT(1) 'table2' FROM table2 GROUP BY name2) a
INNER JOIN (SELECT name1,COUNT(1) 'table1' FROM [table1] GROUP BY name1) b ON a.name2=b.name1
ELSE
SELECT '无相同值'
----------------结果----------------------------
/*
id NAME table1 table2
-------------------- ---- ----------- -----------
1 123 1 2
2 789 1 1
*/