【问题标题】:Data retrieval to regular variable数据检索到常规变量
【发布时间】:2021-06-07 22:25:36
【问题描述】:

所以我之前关于计算 datetime2 部分出现次数的问题给我留下了几个问题。 How to count occurrences of parts of datetime2

我最后一个问题的最终格式是

date                          user_id   yearCount
-------                       -------   -----------
2020-11-12 00:00:00.0000000     12          2
2020-05-23 00:00:00.0000000     12          2
2021-06-01 00:00:00.0000000     12          2
2021-04-15 00:00:00.0000000     12          2
2022-02-20 00:00:00.0000000     12          3
2022-01-20 00:00:00.0000000     12          3
2022-04-20 00:00:00.0000000     12          3

这是由 @sticky bit

创建的
SELECT date,
       user_id,
       count(*) OVER (PARTITION BY year(date),
                                   user_id) yearcount
       FROM table
       WHERE user_id = @user_id;

我现在想弄清楚的是,如果我在进行查询,我如何将特定年份的 yearCount 获取到变量中?假设我只想查询 2022 年(int)。所以查询完成后,我希望变量 (让我们说@yearCountAmount) 的值为 3。

【问题讨论】:

    标签: sql sql-server date tsql datetime


    【解决方案1】:

    你会使用聚合:

    SELECT @yearcount = COUNT(*) 
    FROM table
    WHERE user_id = @user_id AND
          YEAR(date) = 2022;
    

    我可能还建议将日期逻辑编写为:

    SELECT @yearcount = COUNT(*) 
    FROM table
    WHERE user_id = @user_id AND
          date >= '2022-01-01' AND
          date < '2023-01-01';
    

    【讨论】:

      【解决方案2】:

      在下面的代码中,您将传入 user_id 和年份,它会返回变量 yearCountAmount。我更改了您最初必须替换 count 逻辑的代码,并创建了一个由 SUM 封装的 case 语句。

      DECLARE @user_id int = 12
      DECLARE @Year INT = 2022
      DECLARE @yearCountAmount INT
      
      SET @yearCountAmount = (SELECT SUM(case when YEAR(date) = @year then 1 end) 
                              FROM table
                              WHERE user_id = @user_id
                                 AND YEAR(date) = @Year)
      
      SELECT @yearCountAmount
      

      【讨论】:

      • 你已经拥有GROUP BY user_id,为什么还要拥有WHERE user_id = @user_id
      • @Squirrel 你说得对,我不需要 group by,因为它已经在哪里了。我修复了我的代码。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多