包含工作日的 SQL 查询
我想知道创建按过去 7 天分组的报告的最佳方式是什么 - 但不是每天都有数据。例如:
2010 年 8 月 1 日 | 0 2010 年 8 月 2 日 | 5 2010 年 8 月 3 日 | 6 2010 年 8 月 4 日 | 10 2010 年 8 月 5 日 | 0 2010 年 8 月 6 日 | 11 2010 年 8 月 7 日 | 1
唯一的选择是创建一个包含这些日期的虚拟表并将它们连接在一起?
谢谢
I would like to know what is the best way of creating a report that will be grouped by the last 7 days - but not every day i have data. for example:
08/01/10 | 0
08/02/10 | 5
08/03/10 | 6
08/04/10 | 10
08/05/10 | 0
08/06/10 | 11
08/07/10 | 1
is the only option is to create a dummy table with those days and join them altogether?
thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试这样的事情
Try something like this
许多人会建议动态创建一系列日期的方法,然后您可以加入这些日期。这肯定会起作用,但根据我的经验,日历表是最佳选择。这将使 SQL 变得简单和通用,但代价是维护日历表。
将来的某个时候,会有人过来要求提供另一份不包括周末的报告。然后,您必须为周末创建动态天数生成帐户。然后有人会要求提供不包括公共假期的工作日,此时您别无选择,只能创建一个日历表。
我建议你硬着头皮创建一个日历表来加入。预先填充每个日期,如果您想提前考虑,请添加“工作日”列,如果您的公司使用非标准周数进行报告,甚至可能添加周数
Many people will suggest methods for dynamically creating a range of dates that you can then join against. This will certainly work but in my experience a calendar table is the way to go. This will make the SQL trivial and generic at the cost of maintaining the calendar table.
At some point in the future someone will come along and ask for another report that excludes weekends. You then have to make your dynamic days generation account for weekends. Then someone will ask for working-days excluding public-holidays at which point you have no choice but to create a calendar table.
I would suggest you bite the bullet and create a calendar table to join against. Pre-populate it with every date and if you want to think ahead then add columns for "Working Day" and maybe even week number if your company uses a non-standard week-number for reporting
您没有提及特定的语言(请提及以获得更详细的答案),但大多数版本的 sql 都有一个用于当前日期的函数(例如 GetDate())。您可以采用该日期,减去 x (7) 天并像这样构建 WHERE 语句。
然后您可以按该日期的一天部分进行分组。
You don't mention the specific language (please do for a more detailed answer), but most versions of sql have a function for the current date (GetDate(), for instance). You could take that date, subtract x (7) days and build your WHERE statement like that.
Then you could GROUP BY the day-part of that date.
选择最后 7 笔交易并将其与您的查询左连接,然后按日期列分组。希望这有帮助。
select the last 7 transactions and left join it with your query and then group by the date column. hope this helps.