我有3张看起来像这样的表:
表3 Game2
我想做的是在Table1中选择所有用户。 然后选择Table1.Name = Table2.Name或Table1.Name = Table3.Name但具有更高的Table2优先级的所有数据,因此如果匹配Table1.Name = Table2.Name,则不会进行表3的连接。然后,当我选择正确的时候,我也想计算得分和犯规的总和。
这是如何在SQL中完成的,是否可能?我正在使用MSSQL
答案 0 :(得分:2)
SELECT
SUM(t1.Score) AS TotalScore,
SUM(COALESCE(t2.Fouls, t3.Fouls)) AS TotalFouls
FROM Table1 t1
LEFT JOIN Table2 t2 ON t2.Name = t1.Name
LEFT JOIN Table3 t3 ON t3.Name = NULLIF(t1.Name, t2.Name)
答案 1 :(得分:0)
以下内容为您提供了很多帮助。不过,我不确定你是想要每用户还是整体聚合。
此外 - 如果您要使用Game3,Game4等,那么您最好的选择是更改您的桌面设计,而不是进一步使这(和其他)查询复杂化。
SELECT SUM(U.Score) AS Score,
SUM(Fouls.Fouls) AS Fouls
FROM dbo.Users U
INNER JOIN (
SELECT COALESCE(G.Name, G2.Name) AS Name,
COALESCE(G.Fouls, G2.Fouls) AS Fouls
FROM dbo.Game G
FULL JOIN dbo.Game2 G2
ON G.Name = G2.Name
) Fouls
ON U.Name = Fouls.Name
答案 2 :(得分:0)
您可以通过在连接到Table3 Table2.Name IS NULL
的条件中指定连接到表2。如果你想要每个球员的总得分和犯规,你可以这样做:
SELECT derived_table.Name, SUM(derived_table.Score), SUM(derived_table.Fouls)
FROM (
SELECT Name = Table1.Name, Score = Table1.Score,
Fouls = COALESCE(Table2.Fouls, Table3.Fouls)
FROM Table1
LEFT OUTER JOIN Table2 ON Table2.Name = Table1.Name
LEFT OUTER JOIN Table3 ON Table3.Name = Table1.Name
AND Table2.Name IS NULL
WHERE Table2.Name IS NOT NULL OR Table3.Name IS NOT NULL
) derived_table
GROUP BY derived_table.Name
总计:
SELECT SUM(derived_table.Score), SUM(derived_table.Fouls)
FROM (
SELECT Score = Table1.Score,
Fouls = COALESCE(Table2.Fouls, Table3.Fouls)
FROM Table1
LEFT OUTER JOIN Table2 ON Table2.Name = Table1.Name
LEFT OUTER JOIN Table3 ON Table3.Name = Table1.Name
AND Table2.Name IS NULL
WHERE Table2.Name IS NOT NULL OR Table3.Name IS NOT NULL
) derived_table