给出一个如下表:
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"));
答案 0 :(得分:1)
你必须对TYPE和DEPT进行分组,并将USER放在where子句中:
select TYPE, DEPT, count(*) as TOTAL
from table1 where USER = 'Team1'
group by TYPE, DEPT
having TOTAL > 0
答案 1 :(得分: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
的项目不属于群组来源。
答案 2 :(得分: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