1

在以下查询方面需要帮助

此刻显示按年度季度分组的具有“工作时间”的用户列表。我还想按工作天数求和 - 问题是每天可以有不止一行,所以“onsitedate”的总和不正确。我不能按“天”分组,因为结果需要按年度季度显示。

sql

SELECT 
  username,
  DatePart ('q', [onsitedate]) AS [qtr],
  SUM(onsitehours),
  SUM(onsitedate)
FROM
  clocktable 
WHERE onsitedate BETWEEN #2013-01-01# AND #2013-12-31#
GROUP BY username, DatePart('q',[onsitedate]) 
ORDER BY username, DatePart('q',[onsitedate]) 

让我知道是否需要更多信息和 TQ

更新

如前所述,我应该在 sitedate 行(错字)上使用 COUNT

SELECT 
  username,
  DatePart ('q', [onsitedate]) AS [qtr],
  SUM(onsitehours),
  **COUNT(onsitedate)**
FROM

但是,如果同一日期存在两条记录,那么我希望计数为 1

示例数据如下:

username        onsitedate         onsitehours
-----------------------------------------------
bob             01/09/2013         10
bob             01/09/2013         2
fred            01/09/2013         12
jim             01/09/2013         10
jim             02/09/2013         5

所需资源

username    qtr    onsitedate_count         onsitehours_sum
--------------------------------------------------------- 
bob         3      1                        12
fred        3      1                        12
jim         3      2                        15

如您所见 - 尽管在 2013 年 1 月 9 日有两条 bob 记录,但 onsitedate_count 仍然为 1,因为它们是同一天

也尝试跟随,以便首先将日子分组,但没有快乐

GROUP BY tech_name, DatePart('d',[on_site_date]), DatePart('q',[on_site_date]) 
4

2 回答 2

2

首先创建一个查询来对 和 的每个onsitehours组合求和。usernameonsitedate

SELECT 
    username,
    DatePart ('q', [onsitedate]) AS [qtr],
    onsitedate,
    SUM(onsitehours) AS SumOfonsitehours
FROM
    clocktable 
WHERE onsitedate BETWEEN #2013-01-01# AND #2013-12-31#
GROUP BY username, DatePart('q',[onsitedate]), onsidedate;

然后将其用作子查询并计算日期并再次对 和 的每个组合计算小时usernameqtr

SELECT
    sub.username,
    sub.qtr,
    Count(sub.onsitedate) AS onsitedate_count,
    Sum(sub.SumOfonsitehours) AS onsitehours_sum
FROM
    (
        SELECT 
            username,
            DatePart ('q', [onsitedate]) AS [qtr],
            onsitedate,
            SUM(onsitehours) AS SumOfonsitehours
        FROM
            clocktable 
        WHERE onsitedate BETWEEN #2013-01-01# AND #2013-12-31#
        GROUP BY username, DatePart('q',[onsitedate]), onsitedate
    ) AS sub
GROUP BY sub.username, sub.qtr
ORDER BY sub.username, sub.qtr;

使用您的clocktable示例数据,该查询将返回您在 Access 2007 中请求的输出。

于 2013-09-23T12:07:54.853 回答
0

只是不要求和(onsitedate)。如果我正确理解你的问题

SELECT 
 a.username,
 DatePart ('q', a.[onsitedate]) AS [qtr],
 COUNT(b.[onsitedate]) onsitedate_count,
 SUM(a.onsitehours)
FROM clocktable a
  join (SELECT username, [onsitedate])
        FROM clocktable GROUP BY username,[onsitedate]) b
    on a.username = b.username
WHERE a.onsitedate BETWEEN #2013-01-01# AND #2013-12-31#
GROUP BY a.username, DatePart('q',a.[onsitedate]), b.onsitedate_count
ORDER BY a.username, DatePart('q',a.[onsitedate]) 
于 2013-09-20T15:40:11.190 回答