我正在尝试在SQL Server 2014中编写一个查询,该查询计算两个表中的行之间的重合次数(但只是当这些重合次数大于1时)到新列中。结构是这样的:
表-A:
================
c1 | c2 | c3 | c411 | 30 | 70 | 90个
20 | 80 | 95 | 99个
15 | 39 | 40 | 41个
......表-B:
================
n1 | n2 | n3 | n430 | 65 | 90 | 95个
20 | 80 | 90 | 99个
15 | 80 | 95 | 99个
...
我希望在table_a
中的列之后在查询中添加一列,如下所示:
查询:
================
c1 | c2 | c3 | c4 | c511 | 30 | 70 | 90 | 2
20 | 80 | 95 | 99 | 6
15 | 39 | 40 | 41 | 0
......
换句话说,对于table_a
中的每一行,检查table_b
中每行匹配的数量,然后将所有大于1的结果相加并粘贴到table_a
中的行旁边。
我有以下代码,但输出错误:
SELECT TOP (100) PERCENT dbo.table_a.c1, dbo.table_a.c2,
dbo.table_a.c3, dbo.table_a.c4, dbo.table_a.c5, dbo.table_a.c6,
COUNT('c1 = n1 or n2 or n3 or n4 or n5 or n6')
+ COUNT('c2 = n1 or n2 or n3 or n4 or n5 or n6')
+ COUNT('c3 = n1 or n2 or n3 or n4 or n5 or n6')
+ COUNT('c4 = n1 or n2 or n3 or n4 or n5 or n6')
+ COUNT('c5 = n1 or n2 or n3 or n4 or n5 or n6')
+ COUNT('c6 = n1 or n2 or n3 or n4 or n5 or n6') AS c5
FROM dbo.table_a CROSS JOIN dbo.[table_b]
GROUP BY dbo.table_a.c1, dbo.table_a.c2, dbo.table_a.c3, dbo.table_a.c4,
dbo.table_a.c5, dbo.table_a.c6
HAVING (COUNT('c1 = n1 or n2 or n3 or n4 or n5 or n6')
+ COUNT('c2 = n1 or n2 or n3 or n4 or n5 or n6')
+ COUNT('c3 = n1 or n2 or n3 or n4 or n5 or n6')
+ COUNT('c4 = n1 or n2 or n3 or n4 or n5 or n6')
+ COUNT('c5 = n1 or n2 or n3 or n4 or n5 or n6')
+ COUNT('c6 = n1 or n2 or n3 or n4 or n5 or n6') > 1)
ORDER BY c5 DESC
任何帮助都会受到赞赏,谢谢!
答案 0 :(得分:2)
;with cte(n) as(
select n1 from table_b union all
select n2 from table_b union all
select n3 from table_b union all
select n4 from table_b
)
,counted(n, c) as(
select n, c = count(n) from cte group by n
)
select
a.*, b.cc
from table_a a
cross apply(
select cc = sum(case when c > 1 then c else 0 end)
from counted
where
n = a.c1
or n = a.c2
or n = a.c3
or n = a.c4
)b