我一直在尝试使用我在SQL server
中构建的以下示例来完全理解联接DECLARE @tablePlace TABLE (ID INT, someplace varchar(10))
DECLARE @tableType TABLE (ID INT, sometype varchar(10))
DECLARE @tableOrders TABLE (ID INT, type int , place int)
INSERT INTO @tablePlace (ID, someplace) values (1,'Place A')
INSERT INTO @tablePlace (ID, someplace) values (2,'Place B')
INSERT INTO @tableType (ID, sometype) VALUES (1,'Type 1')
INSERT INTO @tableType (ID, sometype) VALUES (2,'Type 2')
INSERT INTO @tableType (ID, sometype) VALUES (3,'Type 3')
INSERT INTO @tableType (ID, sometype) VALUES (4,'Type 4')
INSERT INTO @tableOrders (ID, place, type) values (1 , 1 , 1) -- PLACE A TYPE 1
INSERT INTO @tableOrders (ID, place, type) values (2 , 1 , 2) -- PLACE A TYPE 2
INSERT INTO @tableOrders (ID, place, type) values (3 , 2 , 2) -- PLACE B TYPE 2
现在我要做的是链接三个表以获得以下结果
╔═════════╦════════╦═══════╗
║ PLACE ║ TYPE ║ COUNT ║
╠═════════╬════════╬═══════╣
║ PLACE A ║ TYPE 1 ║ 1 ║
║ PLACE A ║ TYPE 2 ║ 1 ║
║ PLACE A ║ TYPE 3 ║ 0 ║
║ PLACE A ║ TYPE 4 ║ 0 ║
║ PLACE B ║ TYPE 1 ║ 0 ║
║ PLACE B ║ TYPE 2 ║ 1 ║
║ PLACE B ║ TYPE 3 ║ 0 ║
║ PLACE B ║ TYPE 4 ║ 0 ║
╚═════════╩════════╩═══════╝
所以我要做的就是链接两个地方,并根据从@tableorders
表中检索到的记录显示每种类型的计数。
到目前为止我的查询:
SELECT place.someplace,
type.sometype,
Count(*) AS count
FROM @tableOrders orders
INNER JOIN @tableplace place
ON orders.place = place.id
INNER JOIN @tabletype type
ON place.id = type.id
GROUP BY someplace,
sometype
ORDER BY someplace,
sometype
有人可以解释我应该遵循的逻辑来实现我想要的结果吗?提前谢谢!
答案 0 :(得分:3)
您希望交叉连接生成行。然后left join
(或相关子查询)获取值:
select p.someplace, t.sometype, count(o.id) as count
from @tableplace p cross join
@tabletype t left join
@tableOrders o
on o.type = t.id and o.place = p.id
group by p.someplace, t.sometype
order by p.someplace, t.sometype;
答案 1 :(得分:2)
试试这个:
SELECT place.someplace, [type].sometype , T.cnt
FROM @tablePlace place
CROSS join @tabletype [type]
OUTER APPLY
( SELECT COUNT(1) cnt
FROM @tableOrders tableOrders
WHERE tableOrders.place=place.ID AND tableOrders.[type] = [type].ID
)T
ORDER BY someplace,sometype
输出:
Place A Type 1 1
Place A Type 2 1
Place A Type 3 0
Place A Type 4 0
Place B Type 1 0
Place B Type 2 1
Place B Type 3 0
Place B Type 4 0
答案 2 :(得分:1)
使用CROSS JOIN
生成MxN表(将所有地点与类型相关联),然后使用LEFT JOIN
生成订单表以获取每对(someplace, sometype)
的计数:
select tp.someplace, tt.sometype, count(to.id) as count
from @tablePlace tp
cross join @tableType tt
left join @tableOrders to on
to.place = tp.id and to.type = tt.id
group by tp.someplace, tt.sometype
order by tp.someplace, tt.sometype
答案 3 :(得分:0)
试试这个:
SELECT A.someplace,B.sometype,COUNT(C.ID) count_val FROM @tablePlace A CROSS JOIN
@tableType B LEFT JOIN @tableOrders C ON C.place = A.ID AND C.type = B.ID
GROUP BY someplace,sometype
希望它有所帮助。 :)