【问题标题】:SELECTING records based on unique date and counting how many records on that date根据唯一日期选择记录并计算该日期的记录数
【发布时间】:2021-04-06 05:55:00
【问题描述】:

我有一张要简化的表格。这是它的样子:

tid     session    pos       dateOn
-----------------------------------------------
1         23        0        12/24/2020 1:00:00
2         23        1        12/24/2020 1:01:23
3         12        0        12/24/2020 1:02:43
4         23        2        12/24/2020 1:04:01
5         23        3        12/24/2020 1:04:12
6         45        0        12/26/2020 4:23:15

这张表告诉我,2020 年 12 月 24 日有 2 个独特的会话,12/26 有 1 个。

我如何编写我的 SQL 语句才能得到这样的结果:

date             recordCount
----------------------------
12/24/2020            2
12/26/2020            1

【问题讨论】:

标签: sql sql-server sql-server-2008


【解决方案1】:

您应该能够简单地转换为日期和聚合:

select convert(date, dateon), count(distinct session)
from t
group by convert(date, dateon)
order by convert(date, dateon);

【讨论】:

  • 甜蜜!这正是我需要的……至少我认为。目前数据库中只有 1 条记录,但随着它的积累,我会知道更多。如果我想按月过滤,我该怎么做? WHERE month(dateOn)='12' AND year(dateOn)='2020'?
  • 你会使用where dateOn >= '2020-12-01' and dateOn < '2021-01-01'
  • 听起来像是一个计划。有理由不使用我写的方式吗?我的意思是月份()和年份()?
  • @Damien。 . .这会阻止使用索引。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多