日期:2014-05-16  浏览次数:20396 次

如何选出两个表中同一字段相同值出现的值和次数?
table1:
id name1
1  123
2  456
3  789
4  012


table2:
id name2
1  098
2  123
3  789
4  123

我想查询出table1和table2中name字段是否有一样的值,如果有,则列出该值的内容和在2个表里出现的次数,如果没有,输出“无相同的值”,谢谢

result:

id name table1 table2
1  123   1     2
2  789   1     1
------解决方案--------------------
----------------------------------------------------------------
-- 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
*/