草庐IT

mysql - 如何使用间隔中的年和月动态显示一行中的零?

coder 2023-10-19 原文

我正在尝试创建一个查询以在 SET YEAR and MONTH 时以 12 个月的间隔显示计数(年和月是动态值 - 间隔是 12 个月的静态值).

例如:设置月 = 12 和年 = 2013

This will count from 2013-12-01 to 2014-11-30

其他示例:设置月 = 1 和年 = 2014

This will count from 2014-01-01 to 2014-12-31

我创建了这个 demo但也想在行数不在表中时显示 0,这里我使用了 COALESCE:

SET @var_year = '2013';
SET @var_month = '12';

SET @from = STR_TO_DATE(CONCAT(@var_year, '/', @var_month, '/01'), '%Y/%m/%d');
SET @to = DATE_ADD(@from, INTERVAL 12 MONTH);

SELECT COALESCE(count(created_at), 0) AS count_all,
       year(created_at) as actual_year,
       month(created_at)as actual_month 
FROM creations
WHERE created_at BETWEEN @from AND @to
GROUP BY month(created_at),year(created_at)
ORDER BY year(created_at),month(created_at) ASC

但不幸的是得到了这个结果:

count_all   actual_year actual_month
1               2013         12
3               2014          1
2               2014          2
1               2014          3
1               2014          4
1               2014          5
1               2014          6
2               2014          8
1               2014          9
1               2014         10
1               2014         11

我期望这样的结果:

count_all   actual_year actual_month
1               2013         12
3               2014          1
2               2014          2
1               2014          3
1               2014          4
1               2014          5
1               2014          6
0               2014          7     <------ HERE I WANT 0 WHEN IS NOT IN DB
2               2014          8
1               2014          9
1               2014         10
1               2014         11

我创建了这个 live demo using month = 12 and year = 2013 ,它确实有效,但在测试和更改月份或年份值后,得到了错误的计数,因此查询无法正常工作,例如这个 demo using month= 1 and year =2013 isn't working correctly

SET @var_year = '2014';
SET @var_month = '1';

SET @from = STR_TO_DATE(CONCAT(@var_year, '/', @var_month, '/01'), '%Y/%m/%d');
SET @to = DATE_ADD(@from, INTERVAL 12 MONTH);

SELECT IFNULL(counter,0) as counter, literals.y AS actual_year, literals.m AS actual_month
FROM (
  SELECT @var_month AS m, @var_year + 0 AS y
  UNION SELECT IF((@var_month + 1) % 12, (@var_month + 1) % 12, 12) AS m, @var_year + ((@var_month + 1) DIV 12) AS y
  UNION SELECT IF((@var_month + 2) % 12, (@var_month + 2) % 12, 12) AS m, @var_year + ((@var_month + 2) DIV 12) AS y
  UNION SELECT IF((@var_month + 3) % 12, (@var_month + 3) % 12, 12) AS m, @var_year + ((@var_month + 3) DIV 12) AS y
  UNION SELECT IF((@var_month + 4) % 12, (@var_month + 4) % 12, 12) AS m, @var_year + ((@var_month + 4) DIV 12) AS y
  UNION SELECT IF((@var_month + 5) % 12, (@var_month + 5) % 12, 12) AS m, @var_year + ((@var_month + 5) DIV 12) AS y
  UNION SELECT IF((@var_month + 6) % 12, (@var_month + 6) % 12, 12) AS m, @var_year + ((@var_month + 6) DIV 12) AS y
  UNION SELECT IF((@var_month + 7) % 12, (@var_month + 7) % 12, 12) AS m, @var_year + ((@var_month + 7) DIV 12) AS y
  UNION SELECT IF((@var_month + 8) % 12, (@var_month + 8) % 12, 12) AS m, @var_year + ((@var_month + 8) DIV 12) AS y 
  UNION SELECT IF((@var_month + 9) % 12, (@var_month + 9) % 12, 12) AS m, @var_year + ((@var_month + 9) DIV 12) AS y
  UNION SELECT IF((@var_month +10) % 12, (@var_month +10) % 12, 12) AS m, @var_year + ((@var_month +10) DIV 12) AS y
  UNION SELECT IF((@var_month +11) % 12, (@var_month +11) % 12, 12) AS m, @var_year + ((@var_month +11) DIV 12) AS y)  
  AS literals
  LEFT JOIN
  (SELECT count(*) as counter, year(created_at) y, month(created_at) as m 
   FROM creations WHERE created_at BETWEEN @from AND @to GROUP BY month(created_at),year(created_at)
   ORDER BY year(created_at),month(created_at) ASC 
 ) AS counts
 ON literals.m = counts.m AND literals.y = counts.y;

我花了几个月的时间搜索有关如何处理这个问题的信息。

如果有人可以帮助我,是无法解决还是其他技巧或查询?

最佳答案

不错的拼图:)

您可以生成一个表,其中包含 12 个月间隔所需的年和月,然后对其进行外部联接:

SET @var_year = '2013'
SET @var_month = '12'

SELECT @row := @row + (case when right(@row,2) = "12" then 89 else 1 end) as YearMonth 
FROM 
(select 0 union all select 1 union all select 3 union all 
 select 4 union all select 5 union all select 6 union all 
 select 6 union all select 7 union all select 8 union all 
 select 9 union all select 10 union all select 11) t,
(SELECT @row:=CONCAT(@var_year,right(concat('0',(@var_month-1)),2))) r

将给予:

| YearMonth |
|-----------|
|    201312 |
|    201401 |
|    201402 |
|    201403 |
|    201404 |
|    201405 |
|    201406 |
|    201407 |
|    201408 |
|    201409 |
|    201410 |
|    201411 |

那么试试这个(以 2014 年为年,1 为月的示例):

SQL Fiddle

MySQL 5.5 架构设置:

CREATE TABLE creations(`id` int, `created_at` date )
;

INSERT INTO creations
    (`id`, `created_at`)
VALUES
    (1, '2013-12-11'),
    (2, '2014-01-11'),
    (3, '2014-01-21'),
    (4, '2014-01-12'),
    (5, '2014-02-22'),    
    (6, '2014-02-13'),
    (7, '2014-03-12'),    
    (8, '2014-04-23'),
    (9, '2014-05-23'),
    (10,'2014-06-23'),
    (11,'2014-08-23'),    
    (12,'2014-08-23'),
    (13,'2014-09-23'),
    (14,'2014-10-23'),    
    (15,'2014-11-23'),        
    (16,'2014-12-23')         
;

**查询**:

SET @var_year = '2014'
SET @var_month = '1'

SELECT count(created_at) AS count_all,
       left(YearMonth,4) as actual_year,
       right(YearMonth,2) as actual_month 
FROM (
SELECT @row := @row + (case when right(@row,2) = "12" then 89 else 1 end) as YearMonth FROM 
(select 0 union all select 1 union all select 3 union all 
 select 4 union all select 5 union all select 6 union all 
 select 6 union all select 7 union all select 8 union all 
 select 9 union all select 10 union all select 11) t,
(SELECT @row:=CONCAT(@var_year,right(concat('0',(@var_month-1)),2))) r
) as YearMonthTable
LEFT OUTER JOIN creations ON
  CONCAT(year(created_at),right(concat('0',month(created_at)),2)) = YearMonth
GROUP BY YearMonth
ORDER BY YearMonth ASC

Results :

| count_all | actual_year | actual_month |
|-----------|-------------|--------------|
|         3 |        2014 |           01 |
|         2 |        2014 |           02 |
|         1 |        2014 |           03 |
|         1 |        2014 |           04 |
|         1 |        2014 |           05 |
|         1 |        2014 |           06 |
|         0 |        2014 |           07 |
|         2 |        2014 |           08 |
|         1 |        2014 |           09 |
|         1 |        2014 |           10 |
|         1 |        2014 |           11 |
|         1 |        2014 |           12 |

已编辑:

您也可以创建表而不是每次都在子查询中生成它:

SQL Fiddle

MySQL 5.5 架构设置:

CREATE TABLE YearMonthTable(`tblYear` int, `tblMonth` int)
;

INSERT INTO YearMonthTable
    (`tblYear`,`tblMonth`)
VALUES
    (2013,12),
    (2014,1),
    (2014,2),    
    (2014,3),    
    (2014,4),
    (2014,5),
    (2014,6),
    (2014,7),    
    (2014,8),
    (2014,9),
    (2014,10),    
    (2014,11),        
    (2014,12),
    (2015,1),
    (2015,2),    
    (2015,3),    
    (2015,4),
    (2015,5)
;

查询:

SET @var_year = '2014'
SET @var_month = '1'

SET @from = STR_TO_DATE(CONCAT(@var_year, '/', @var_month, '/01'), '%Y/%m/%d')
SET @to = DATE_ADD(DATE_ADD(@from, INTERVAL 12 MONTH), INTERVAL -1 DAY)

SELECT count(created_at) AS count_all,
       tblYear as actual_year,
       tblMonth as actual_month 
FROM YearMonthTable
LEFT OUTER JOIN creations ON year(created_at) = tblYear AND 
                             month(created_at) = tblMonth
WHERE STR_TO_DATE(CONCAT(tblYear, '/', tblMonth, '/01'), '%Y/%m/%d') 
                                                    BETWEEN @from AND @to                               
GROUP BY tblMonth, tblYear
ORDER BY tblYear, tblMonth

Results :

| count_all | tblYear | tblMonth |
|-----------|---------|----------|
|         3 |    2014 |        1 |
|         2 |    2014 |        2 |
|         1 |    2014 |        3 |
|         1 |    2014 |        4 |
|         1 |    2014 |        5 |
|         1 |    2014 |        6 |
|         0 |    2014 |        7 |
|         2 |    2014 |        8 |
|         1 |    2014 |        9 |
|         1 |    2014 |       10 |
|         1 |    2014 |       11 |
|         1 |    2014 |       12 |

关于mysql - 如何使用间隔中的年和月动态显示一行中的零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30082636/

有关mysql - 如何使用间隔中的年和月动态显示一行中的零?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  4. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  5. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  6. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  7. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  8. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  9. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  10. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

随机推荐