MS Access SQL 运行总数

Posted

技术标签:

【中文标题】MS Access SQL 运行总数【英文标题】:MS Access SQL Running Total 【发布时间】:2018-08-14 22:14:15 【问题描述】:

我摸不着头脑,因为我不知道如何在 MS Access 中创建运行总和,我尝试了 IIF 语句、DSUM 语句和子查询(这是我的首选)

很简单,我有一份足球队名单、他们的比赛日期和他在每场比赛中获得的积分,我想创建一个运行总分。

我的查询没有按应有的方式计算运行总和,它只是计算当前游戏。

以下是我尝试的代码,有人可以帮忙吗?

SELECT Team, FORMAT(mDate, "yyyy-mm-dd") AS Match_Date, Pts, 
SUM(IIF(FORMAT(mDate, "yyyy-mm-dd") <= FORMAT(mDate, "yyyy-mm-dd"),Pts)) AS Total_Pts
FROM 
(SELECT * FROM
(SELECT home_team AS Team, match_date AS mDate, IIF(home_goals > away_goals,3,IIF(home_goals = away_goals,1,0)) AS Pts FROM A WHERE league = "Premiership" AND season = "2016 - 2017" AND home_team = "Arsenal"  
UNION  
SELECT away_team AS Team, match_date AS mDate, IIF(home_goals < away_goals,3,IIF(home_goals = away_goals,1,0)) AS Pts FROM A WHERE league = "Premiership" AND season = "2016 - 2017" AND away_team = "Arsenal")  AS Filter ORDER BY 2 DESC)  AS Test
GROUP BY Team, FORMAT(mDate, "yyyy-mm-dd"), Pts
ORDER BY 2 DESC;

【问题讨论】:

您能提供一些示例数据并期待结果吗? 【参考方案1】:

首先:不要将日期格式化为字符串并将这些字符串当作日期进行比较。

然后:为了能够将UNION 查询加入到自身,查询必须编写两次,每次都有自己的别名。其中一个查询将用于当前游戏记录,另一个用于构建积分的运行总和。连接两边的Team 必须相等,“running”查询的mDate 必须小于或等于当前游戏的mDate。由于UNION第一部分的记录与第二部分的记录不同,可以使用UNION ALL加快查询速度:

SELECT Games.Team, Games.mDate, Games.Pts, SUM(Runnings.Pts) AS Total_Pts
FROM
(
    SELECT home_team AS Team, match_date AS mDate, IIF(home_goals > away_goals,3,IIF(home_goals = away_goals,1,0)) AS Pts
    FROM A WHERE league = "Premiership" AND season = "2016 - 2017" AND home_team = "Arsenal"
    UNION ALL
    SELECT away_team AS Team, match_date AS mDate, IIF(home_goals < away_goals,3,IIF(home_goals = away_goals,1,0)) AS Pts
    FROM A WHERE league = "Premiership" AND season = "2016 - 2017" AND away_team = "Arsenal"
) AS Games
INNER JOIN
(
    SELECT home_team AS Team, match_date AS mDate, IIF(home_goals > away_goals,3,IIF(home_goals = away_goals,1,0)) AS Pts
    FROM A WHERE league = "Premiership" AND season = "2016 - 2017" AND home_team = "Arsenal"
    UNION ALL
    SELECT away_team AS Team, match_date AS mDate, IIF(home_goals < away_goals,3,IIF(home_goals = away_goals,1,0)) AS Pts
    FROM A WHERE league = "Premiership" AND season = "2016 - 2017" AND away_team = "Arsenal"
) AS Runnings ON Games.Team = Runnings.Team AND Games.mDate >= Runnings.mDate
GROUP BY Games.Team, Games.mDate, Games.Pts
ORDER BY Games.Team, Games.mDate;

【讨论】:

这工作完美,感谢一百万,非常感谢您的帮助。

以上是关于MS Access SQL 运行总数的主要内容,如果未能解决你的问题,请参考以下文章

MS Access SQL 查询 - 将所有表与多个表联合 - 重复字段

使用 ODBC 连接到 MYSQL 在 MS-Access 中运行 SQL 时出错

MS-Access 获取字段值,通过 VBA 函数运行,并发送到 SQL

MS access运行SQL不插入数据,没有错误

通过运行 SQL 查询在 MS Access 2012 上更改年份日期格式的错误

Sql 注入 MS Access