SQL 我们可以使用具有相同字段名的 group by 和 where 条件吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7073497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can we use group by and where condition with same fieldname
提问by Tom Crusie
I have a requirement like have to pull all records in the date range the user selected, selecting all employees who started from 15-Jan-2011 to 20-Aug-2011 and group by date.
我有一个要求,比如必须提取用户选择的日期范围内的所有记录,选择从 2011 年 1 月 15 日到 2011 年 8 月 20 日开始并按日期分组的所有员工。
How should I write SQL query for this:
我应该如何为此编写 SQL 查询:
SELECT *
FROM employees
WHERE startdate >= '15-jan-2011'
AND startdate <= '20-aug-2011'
GROUP BY startdate
回答by Derek Kromm
Absolutely. It will result in filtering the records on your date range and then grouping it by each day where there is data.
绝对地。这将导致过滤日期范围内的记录,然后按有数据的每一天对其进行分组。
It should be noted that you will only be able to select the startdate and then whatever aggregates you're calculating. Otherwise, it should work perfectly fine.
应该注意的是,您只能选择开始日期,然后选择您正在计算的任何聚合。否则,它应该可以正常工作。
For example, this query will give you a count of employees for each startdate:
例如,此查询将为您提供每个开始日期的员工数:
SELECT startdate, count(*)
FROM employees
WHERE startdate >= '15-jan-2011'
AND startdate <= '20-aug-2011'
GROUP BY startdate
回答by Scott
You can, but the "GROUP BY" clause is used for grouping together sets of rows, so it does not make sense for your question (or anything that involves a "SELECT *").
您可以,但是“GROUP BY”子句用于将行集分组在一起,因此它对您的问题(或任何涉及“SELECT *”的问题)没有意义。
To answer your question though:
不过要回答你的问题:
SELECT DATEADD(dd, 0, DATEDIFF(dd,0,StartDate)) AS 'StartDate', <other fields>
FROM Employees
WHERE StartDate BETWEEN '15-Jan-2011' AND '20-Jan-2011'
ORDER BY StartDate
Note: the stripping of the time from the date came from here
注意:从日期中剥离时间来自这里