0

给定一个如下所示的表:

DATE    USER         TYPE        DEPT
3/1/13  Team1        Add         Finance
3/1/13  Team1        Add         Collections
3/2/13  Team1        Delete      Finance
3/2/13  Team1        Delete      Finance
3/2/13  Team1        Delete      Finance
3/3/13  Team1        Delete      Collections
3/3/13  Team1        Change      Finance
3/3/13  Team1        Change      Finance
3/4/13  Team1        Add         Finance
3/5/13  Team1        Delete      Collections

我怎样才能得到这样的输出?

TYPE        DEPT        COUNT
Add         Collections 1
Add         Finance     2
Change      Collections 0 (note: this line could be omitted if COUNT = 0)
Change      Finance     2
Delete      Collections 2
Delete      Finance     3

我还需要指定 USER = Team1 和日期范围。到目前为止,我有以下内容,但它不起作用:

SELECT user, type, Count(*) AS Total
FROM table1
GROUP BY user, type
HAVING (((user)="Team1"));

这给了我:

USER    TYPE    Total
Team1   Add     3
Team1   Change  2
Team1   Delete  5

但不会按 DEPT 分解,我不确定如何指定日期范围。

一如既往,谢谢!!

编辑:我想我想通了:

SELECT User, Type, Dept, Count(*) AS Total
FROM Table1
WHERE (((Date) Between #3/1/2013# And #3/5/2013#))
GROUP BY User, Type, Dept
HAVING (((User)="Team1"));
4

3 回答 3

1

您必须对 TYPE 和 DEPT 进行分组,并将 USER 放在 where 子句中:

select TYPE, DEPT, count(*) as TOTAL
from table1 where USER = 'Team1'
group by TYPE, DEPT
having TOTAL > 0
于 2013-04-01T17:40:37.223 回答
1

GROUP BY您必须使用列进行扩展DEPT

GROUP BY user, type, dept

为了满足日期范围条件添加WHERE部分:

WHERE date >= startDate AND date <= endDate

要获取一个用户的数据,只需添加另一个WHERE条件:

WHERE user = "Team1"

整个查询应如下所示:

SELECT user, type, dept, Count(*) AS Total
FROM table1
WHERE date >= startDate AND date <= endDate AND user = "Team1"
GROUP BY user, type, dept

您不必做任何事情来删除行Total = 0- 它们不会在那里,因为带有那个的项目type并且dept不在组源中。

于 2013-04-01T17:42:31.130 回答
1

我想你可以试试这个。

SELECT Type, Dept, Count(*) AS Total
FROM Table1
WHERE (((Date) Between #3/1/2013# And #3/5/2013#))
AND (((User)="Team1"))
GROUP BY Type, Dept
于 2013-04-01T17:43:30.747 回答