按id获取每日用户数返回错误

7eumitmz  于 2021-07-26  发布在  Java
关注(0)|答案(4)|浏览(242)

我正在尝试从SQLServer表中获取每日唯一用户数。
表的外观示例:

user_id start_timestamp     activity
111     08/25/2020 13:23    aaaa
111     08/25/2020 14:24    bbbb
222     08/25/2020 14:26    cccc
222     08/25/2020 14:28    dddd
333     08/25/2020 14:31    eeee

我要查找的结果表示例:

user_id start_date  count
111     08/25/2020  2
222     08/25/2020  2
333     08/25/2020  1

这就是我尝试过的。”

SELECT 
    [user_id],  
    CONVERT(VARCHAR,[start_timestamp], 23) as [start_date]
    COUNT([user_id]) AS [user_count]
  FROM [dbo].[user_activity]
  GROUP BY [user_id],[start_date]
  ORDER BY [start_date]

我不得不将时间戳中的日期转换为组的日期,但我不断收到错误消息:
列名“开始日期”无效。

7xzttuei

7xzttuei1#

在单个select语句中,不能使用GROUPBY子句中的select子句设置的别名。

SELECT 
    [user_id],  
    CONVERT(VARCHAR,[start_timestamp], 23) as [start_date] --<< established here
    COUNT([user_id]) AS [user_count]
FROM [dbo].[user_activity]
GROUP BY [user_id],[start_date] --<< illegal reuse of alias here
ORDER BY [start_date]

您可以通过简单地重复别名之前的信息来避免这种情况,如下所示

SELECT 
    [user_id],  
    CONVERT(VARCHAR,[start_timestamp], 23) as [start_date] --<< established here
    COUNT([user_id]) AS [user_count]
FROM [dbo].[user_activity]
GROUP BY [user_id],CONVERT(VARCHAR,[start_timestamp], 23) --<< no alias here
ORDER BY [start_date]

我更希望看到您将时间戳转换为日期,而不是转换为字符串。

SELECT 
    [user_id],  
    cast([start_timestamp] as date) as [start_date] --<< alias established here
    COUNT([user_id]) AS [user_count]
FROM [dbo].[user_activity]
GROUP BY [user_id],cast([start_timestamp] as date)
ORDER BY [start_date]
7lrncoxx

7lrncoxx2#

您需要将转换日期列添加到grı按节向上。

SELECT 
    [user_id],  
    CONVERT(VARCHAR,[start_timestamp], 23) as [start_date]
    COUNT([user_id]) AS [user_count]
  FROM [dbo].[user_activity]
  GROUP BY [user_id],CONVERT(VARCHAR,[start_timestamp], 23)
  ORDER BY [start_date]
u5rb5r59

u5rb5r593#

列别名 [start_date] 是在 GROUP BY 进行评估。
而是使用派生表(子查询)首先获取 [start_date] ,然后 GROUP BY .

SELECT 
    [user_id],  
    [start_date]
    COUNT([user_id]) AS [user_count]
FROM
(
  SELECT 
      [user_id],
      CONVERT(VARCHAR,[start_timestamp], 23) as [start_date]
  FROM [dbo].[user_activity]
) dt
GROUP BY [user_id], [start_date]
ORDER BY [start_date]
nkcskrwz

nkcskrwz4#

你不应该改成 varchar 没有时间的约会。改为转换为 date .
正如其他人提到的,不能重用 select 中的别名 group by . 你可以重复同样的话 convert 再说一次,但更好的方法是把它放到 cross apply ,这允许您以后重用它。
您还应该使用适当的表别名。

SELECT 
    u.user_id,  
    v.start_date
    COUNT(user_id) AS user_count
  FROM dbo.user_activity u
  CROSS APPLY (VALUES( CAST(u.start_timestamp AS date) ) v(start_date)
  GROUP BY u.user_id, v.start_date
  ORDER BY v.start_date

相关问题