我有这张桌子:
我从中创建此视图:
这个视图CardId
允许我JOIN
对着Card
表格使用,这样我就可以Count
从任何CardId
. 这是我的 SQL:
SELECT * FROM (
SELECT
si.CardId SourceCardId,
ti.CardId TargetCardId,
(SELECT TOP 1 r.Name
FROM dbo.Relationship r
WHERE r.Id = rac.RelationshipId) [Name],
Count(*) [Count]
FROM dbo.Relationship_AcquiredCard rac
JOIN dbo.AcquiredCard sac ON rac.SourceAcquiredCardId = sac.Id
JOIN dbo.AcquiredCard tac ON rac.TargetAcquiredCardId = tac.Id
JOIN dbo.CardInstance si ON sac.CardInstanceId = si.Id
JOIN dbo.CardInstance ti ON tac.CardInstanceId = ti.Id
GROUP BY si.CardId, ti.CardId, rac.RelationshipId
-- you can probably ignore everything above
) X
CROSS APPLY
(values (X.TargetCardId),
(X.SourceCardId)
) whatdoesthisdo(CardId) --wut
做什么whatdoesthisdo
?我CROSS APPLY
从这个答案中得到了答案。如果我尝试以通常的方式别名,我会收到此错误:
谢谢!