查询月帮助

时间:2010-04-14 20:47:37

标签: mysql

嘿,我需要一些有关如何解决问题的有用提示/建议。我有一个包含“注册”表的数据库。该表的日期格式如下:

2010-04-03 00:00:00

现在假设我在这个数据库中有10条记录:

2010-04-03 00:00:00
2010-01-01 00:00:00
2010-06-22 00:00:00
2010-02-08 00:00:00
2010-02-05 00:00:00
2010-03-08 00:00:00
2010-09-29 00:00:00
2010-11-16 00:00:00
2010-04-09 00:00:00
2010-05-21 00:00:00

我希望每个月都能获得总寄存器......所以按照上面的例子:

Jan = 1
Feb = 2
Mar = 1
Apr = 2
May = 1
Jun = 1
Jul = 0
Aug = 0
Sep = 1
Oct = 0
Nov = 1
Dec = 0

现在我如何使用查询来执行此操作,但不必使用如下查询:

 WHERE left(date, 7) = '2010-01'

并继续这样做12次?我希望它是一个单一的查询调用,并让它将月份访问放入一个数组中,如下所示:

 do until EOF
   theMonthArray[0] = "total for jan"
   theMonthArray[1] = "total for feb"
   theMonthArray[2] = "total for mar"
   theMonthArray[3] = "total for apr"
   ...etc
 loop

除了每个月发布的带有12个查询的示例之外,我无法想到一种方法。

这是我现在的查询。再次,这只填充了一个月,我试图一次性填充所有12个月。

 SELECT count(idNumber) as numVisits, theAccount, signUpDate, theActive
 from userinfo
 WHERE theActive = 'YES'
 AND idNumber = '0203'
 AND theAccount = 'SUB'
 AND left(signUpDate, 7) = '2010-04'
 GROUP BY idNumber
 ORDER BY numVisits;

上面的示例查询输出:

 numVisits | theAccount | signUpDate          | theActive
 2           SUB          2010-04-16 00:00:00   YES

这是正确的,因为我在4月份内有2条记录。

但同样,我试图一次完成所有12个月(在单个查询中),所以与12个不同的查询相比,我不会对数据库服务器征税太多...

更新的 我希望按照以下方式做点什么:

 if NOT rst.EOF
    if left(rst("signUpDate"), 7) = "2010-01" then
        theMonthArray[0] = rst("numVisits")
    end if        

    if left(rst("signUpDate"), 7) = "2010-02" then
        theMonthArray[1] = rst("numVisits")
    end if
    etc etc....
 end if

任何帮助都会很棒! :)

大卫

2 个答案:

答案 0 :(得分:1)

您需要创建一个包含所有月份的派生表,并将其连接到您的查询中,以便在没有条目的月份中获得零计数而不是缺少行。以下查询有点长,但应符合您的要求:

SELECT
    T1.`month`,
    COALESCE(numVisits, 0) AS numVisits
FROM (
    SELECT 1 AS month
    UNION ALL
    SELECT 2
    UNION ALL
    SELECT 3
    UNION ALL
    SELECT 4
    UNION ALL
    SELECT 5
    UNION ALL
    SELECT 6
    UNION ALL
    SELECT 7
    UNION ALL
    SELECT 8
    UNION ALL
    SELECT 9
    UNION ALL
    SELECT 10
    UNION ALL
    SELECT 11
    UNION ALL
    SELECT 12
) AS T1
LEFT JOIN (
    SELECT
        MONTH(signUpDate) AS `month`,
        COUNT(*) AS numVisits
    FROM userinfo
    WHERE theActive = 'YES'
    AND idNumber = '0203'
    AND theAccount = 'SUB'
    AND YEAR(signUpDate) = 2010
    GROUP BY MONTH(signUpDate)
) AS T2 ON T1.`month` = T2.`month`

答案 1 :(得分:0)

好的,明白了。

do until oRecordset.EOF
    theMonth(x) = oRecordset("numVisits")
    oRecordset.movenext
    x = x + 1
loop