mysql - 如何在 case 语句中创建循环

标签 mysql sql function loops case

我有以下 SQL 语句:

DECLARE @time datetime;       
SELECT @time = (select min(CreationDate) from TABLE);

DECLARE @time2 int;       
SELECT @time2 = 15;

select ColumnA, 
(case when CreationDate between @time and DATEADD(MINUTE,@time2***1**,@time) 
          then cast (@time2*1 as int)
      when CreationDate between @time and DATEADD(MINUTE,@time2***2**,@time) 
          then cast (@time2*2 as int)
      when CreationDate between @time and DATEADD(MINUTE,@time2***3**,@time) 
          then cast (@time2*3 as int)
      when CreationDate between @time and DATEADD(MINUTE,@time2***4**,@time) 
          then cast (@time2*4 as int)
      else 0
end) as 'interval', count(1)
from TABLE
 group by 
ColumnA, 
(case when CreationDate between @time and DATEADD(MINUTE,@time2***1**,@time) 
          then cast (@time2*1 as int)
      when CreationDate between @time and DATEADD(MINUTE,@time2***2**,@time) 
          then cast (@time2*2 as int)
      when CreationDate between @time and DATEADD(MINUTE,@time2***3**,@time) 
          then cast (@time2*3 as int)
      when CreationDate between @time and DATEADD(MINUTE,@time2***4**,@time) 
          then cast (@time2*4 as int)
      else 0
end)
  1. 如何在循环中编写 case 语句,以便粗体数字将成为参数 2.我需要循环/函数能够根据 Q.1 中的参数写入所需数量的 case 行

非常感谢!

大家好,

感谢您的回复和评论。 我意识到也许我没有正确解释我的问题。让我再次重新表述一下我的问题。

我有一个 ETL 进程,它运行并填充一个表,该表由显示代码的名为“ColumnA”的列和名为“CreationDate”的创建时间列组成。 我想将结果除以创建时间。有时 15 分钟,有时 20 分钟或任何其他时间间隔。 所以我建立了一个名为“@time”的变量来表示间隔长度是多少。 第一个问题:我不知道ETL过程会运行多长时间,因此我不知道CASE语句中会产生多少行。 第二个问题:CASE语句行数还取决于我在变量“@time”中选择的间隔长度。也就是说,如果该过程需要一个小时,并且“@time”选择的间隔是 15 分钟,那么我必须生成 4 个 CASE 语句行,但如果我选择“@time”为 10 分钟,那么我必须生成 6 个 CASE 语句行... 我可以用参数来完成谁的操作?

预先感谢您的时间和努力。 问候, 艾伦·B.

最佳答案

使用 SQL 时不要考虑循环。想想您想要看到的结果。

如果我正确解释您的请求,您将选择创建日期在给定 @time 和下一小时之间的所有行。对于这些,您可以确定时间片。在您的例子中,它是 15 分钟,您想知道创建日期是在前 15 分钟内(然后您输出 15),还是第二分钟(然后您输出 30)等等。具有其他创建日期的记录,无论是在相关小时之前还是之后,都会给出输出 0。

所以唯一的问题是找到正确的公式,或多或少是:获取以分钟为单位的时间差,除以分钟切片,得到的完整整数将告诉您它是哪个切片,从 0 开始一小时内的第一片。

应该或多或少:

select columna, interval_end_minute, count(*)
from
(
  select
    columna,
    case when creationdate >= @time and creationdate < dateadd(hour,1,@time) then
      (truncate((time_to_sec(datediff(creationdate, @time)) / 60) / @time2, 0) + 1) * @time2
    else 
      0
    end as interval_end_minute
  from table
) data
group by columna, interval_end_minute;

关于mysql - 如何在 case 语句中创建循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35481211/

相关文章:

mysql - 创建事件时出现错误#1064

SQL 多列排序

mysql - SQL检查A和B是否IN(...)

excel - 为什么必须为 Vlookup 打开一些 excel 文档,而不是其他文档?

c++ - 为什么malloc前面有(void*)?

mysql - 使用内部连接更新多个表中的列

java无法连接名称中带有下划线的数据库?

c - c中的表达式

php - Jquery Ajax 调用正在破坏我的数据

sql - 更新一个变量的动态sql语句