我有以下两个单独的语句查询同一个表,在每种情况下,一个select distinct应用于一列,然后另一列求和。
SELECT
HomeTeam, SUM(FTHG)
FROM
(SELECT DISTINCT HomeTeam, FTHG FROM Football_Stats.E0_1617) AS alias_name
GROUP BY
HomeTeam
SELECT
AwayTeam, SUM(FTAG)
FROM
(SELECT DISTINCT AwayTeam, FTAG FROM Football_Stats.E0_1617) AS alias_name
GROUP BY
AwayTeam
select distinct(但不是sum)的结果将是相同的,是否可以将单个查询的组合结果返回到以下内容:
团队SUM(FTHG)SUM(FTAG)
这需要加入两个临时表吗?
道歉我没有发布示例表,我在格式化方面苦苦挣扎。
答案 0 :(得分:0)
一个选项是首先使用UNION ALL添加两个查询结果(但为FTHG和FTAG创建不同的列),然后再按队列组合行...
SELECT Team,SUM(FTHGSum),SUM(FTAGSum)
FROM
((SELECT HomeTeam AS Team,SUM(FTHG) AS FTHGSum,0 AS FTAGSum FROM (SELECT DISTINCT HomeTeam,FTHG FROM ZTesting) T1 GROUP BY HomeTeam)
UNION ALL
(SELECT AwayTeam AS Team,0 AS FTHGSum,SUM(FTAG) AS FTAGSum FROM (SELECT DISTINCT AwayTeam,FTAG FROM ZTesting) T2 GROUP BY AwayTeam)) AS T
GROUP BY Team
注意:很抱歉要问,但是......您知道使用多列DISTINCT
会将区别应用于列组合吗?我觉得很奇怪,在你的查询中,你所获得的目标总和并不是每支球队的所有比赛(你缺少球队得分相同的比赛数)。但当然,我只是猜测,我不知道你的具体案例......
我希望它有所帮助