我有一些示例数据的下表:
表格:TblTestDB
CREATE TABLE TblTestDB (id int,name varchar(100));
INSERT INTO TblTestDB VALUES(1,'Sam'),(2,'Jack'),
(3,'Rock'),(4,'Don'),(5,'Tam');
表格:TblDB1
CREATE TABLE TblDB1 (id int,name varchar(100));
INSERT INTO TblDB1 VALUES(1,'Sam'),(2,'Jack'),
(3,'Rock');
表格:TblDB2
CREATE TABLE TblDB2 (id int,name varchar(100));
INSERT INTO TblDB2 VALUES(1,'Jazz'),(2,'Dsouze'),
(3,'Rock'),(4,'Jack');
表格:TblDB3
CREATE TABLE TblDB3 (id int,name varchar(100));
INSERT INTO TblDB3 VALUES(1,'Sam'),(2,'Jazz'),
(3,'Rock');
我想以以下形式显示结果
TableName Name ID
------------------------------
TblDB1 3 3
TblDB2 2 4
TblDB3 2 3
关于结果集的解释:我想显示在表TblTestDB
和其他表(TblDB1
,TblDB2
,TblDB3
)之间匹配的列值计数。
尝试以下查询:
查询:
SELECT DB,MAX(Name) AS Name, MAX(ID) AS ID
FROM
(
SELECT 'TblDB1' AS DB,COUNT(a.Name) AS Name,0 AS ID
FROM TblTestDB a
INNER JOIN TblDB1 b ON a.Name = b.Name
UNION
SELECT 'TblDB2' AS DB,COUNT(a.Name) AS Name,0 AS ID
FROM TblTestDB a
INNER JOIN TblDB2 b ON a.Name = b.Name
UNION
SELECT 'TblDB3' AS DB,COUNT(a.Name) AS Name,0 AS ID
FROM TblTestDB a
INNER JOIN TblDB3 b ON a.Name = b.Name
UNION
SELECT 'TblDB1' AS DB,0 AS Name,COUNT(a.ID) AS ID
FROM TblTestDB a
INNER JOIN TblDB1 b ON a.ID = b.ID
UNION
SELECT 'TblDB2' AS DB,0 AS Name,COUNT(a.ID) AS ID
FROM TblTestDB a
INNER JOIN TblDB2 b ON a.ID = b.ID
UNION
SELECT 'TblDB3' AS DB,0 AS Name,COUNT(a.ID) AS ID
FROM TblTestDB a
INNER JOIN TblDB3 b ON a.ID = b.ID
) a
GROUP BY DB
问题:我可能会得到10列以上的矩阵/数据透视图,上面的查询随着列列表的增长而增加。 任何使其简短和简单的更好方法。
答案 0 :(得分:2)
SELECT DISTINCT 'TblDB1' AS DB
,COUNT(CASE WHEN a.Name = b.Name THEN 1 ELSE NULL END) AS Name
,COUNT(CASE WHEN a.ID = b.ID THEN 1 ELSE NULL END) AS ID
FROM TblTestDB a
CROSS JOIN TblDB1 b
UNION ALL
SELECT DISTINCT 'TblDB2' AS DB
,COUNT(CASE WHEN a.Name = b.Name THEN 1 ELSE NULL END) AS Name
,COUNT(CASE WHEN a.ID = b.ID THEN 1 ELSE NULL END) AS ID
FROM TblTestDB a
CROSS JOIN TblDB2 b
UNION ALL
SELECT DISTINCT 'TblDB3' AS DB
,COUNT(CASE WHEN a.Name = b.Name THEN 1 ELSE NULL END) AS Name
,COUNT(CASE WHEN a.ID = b.ID THEN 1 ELSE NULL END) AS ID
FROM TblTestDB a
CROSS JOIN TblDB3 b
答案 1 :(得分:0)
这够简单吗?
SELECT
tableName, sum(s.[Name]) as ncnt, max(s.id) as ID
FROM TblTestDB t
cross apply (
SELECT tableName, count(name) as [name], max(id) as ID
FROM (
SELECT 'TblDB1' as tid, * FROM TblDB1
union
SELECT 'TblDB2' as tid, * FROM TblDB2
union
SELECT 'TblDB3' as tid, * FROM TblDB3
) i
where i.name = t.name
group by tableName
) s
group by tableName
不确定您的意思是:“我可能会得到10多个列来显示类似矩阵/数据透视图”。 例如,如果您要添加一个“姓氏”列,应该单独匹配还是与“名称”列组合使用? (前者可能会变得有点复杂...)