Sql 将表1中具有键值的两个表与表2中的所有键值连接起来
我有两张桌子 表1:带有列名Sql 将表1中具有键值的两个表与表2中的所有键值连接起来,sql,sql-server,Sql,Sql Server,我有两张桌子 表1:带有列名键 价值观: 表2:有三列产品,类别,计数 P1-C1-2 P1-C3-4 P2-C1-3 P2-C2-4, P2-C3-8, P3-C3-10, P3-C4-2, 所需输出: P1-C1-2 P1-C2-0 P1-C3-0 P1-C4-0 P2-C1-3 P2-C2-4, P2-C3-8, P2-C4-0, P3-C1-0, P3-C2-0, P3-C3-10, P3-C4-2 有什么办法
键
价值观:
表2:有三列产品
,类别
,计数
P1-C1-2
P1-C3-4
P2-C1-3
P2-C2-4,
P2-C3-8,
P3-C3-10,
P3-C4-2,
所需输出:
P1-C1-2
P1-C2-0
P1-C3-0
P1-C4-0
P2-C1-3
P2-C2-4,
P2-C3-8,
P2-C4-0,
P3-C1-0,
P3-C2-0,
P3-C3-10,
P3-C4-2
有什么办法吗
提前感谢看起来您想使用交叉连接:
SELECT [* | column_list]
FROM table1
CROSS JOIN table2;
您正在寻找
交叉连接
select distinct t2.Product, t1.Key, coalesce(t3.count, 0) as count
from table2 t2 cross join (select [Key] from table1) t1
left join table2 t3
on t3.Product = t2.Product and t1.[key] = t3.Category
select distinct t2.Product, t1.Key, coalesce(t3.count, 0) as count
from table2 t2 cross join (select [Key] from table1) t1
left join table2 t3
on t3.Product = t2.Product and t1.[key] = t3.Category
SELECT t2.Product,t2.Category, case when t2.Category=t1.Category then t2.count ELSE 0 END AS count
FROM table1 t1,table2 t2;