Question

I have this table:

enter image description here

from which I create this View:

enter image description here

This view's CardId allows me to JOIN against the Card table with so I can retrieve the Count from any CardId. Here's my 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

What does whatdoesthisdo do? I got the CROSS APPLY from this answer. If I try to alias in the usual way, I get this error:

enter image description here

Thanks!

Was it helpful?

Solution

It should be clear from the below

SELECT WhatDoesThisDo.CardId
FROM   (VALUES (1),
               (2) ) WhatDoesThisDo(CardId) 

WhatDoesThisDo provides the table alias for the derived table defined by the VALUES clause. It then requires a comma delimited list of all column names (as there is no way of naming them inside the VALUES itself).

In this case it only returns one column so the complete column list is (CardId)

The relevant part of the grammar is

derived_table [ [ AS ] table_alias ] [ ( column_alias [ ,...n ] ) ] 

though the optionality indicated by the square brackets above does not apply with table value constructors.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top