我想获得我在DB中的每个月的统计信息
SELECT monthname(created_at) AS month, YEAR(created_at) AS year, count(*) AS number
FROM tableName
WHERE type_of_user = "someType"
GROUP BY year, month(created_at)
ORDER BY created_at DESC
现在它只给我一个月,但是即使该月我没有任何存储数据,我也需要获取每个月的统计信息
答案 0 :(得分:1)
创建一个calendar
表。您打算使用的每一年,每个月需要输入一次。
然后从日历表中选择,并加入从当前查询中获得的值。使用COALESCE()
将零值放在条目为NULL的位置(例如,tableName
中没有该月份和年份的记录)。
SELECT MONTHNAME(date) as month,
YEAR(date) as year,
COALESCE(number, 0) as number
FROM calendar AS C
LEFT JOIN (
SELECT created_at, COUNT(*) as number
FROM tableName AS T
WHERE T.type_of_user = 'someType'
GROUP BY YEAR(created_at), MONTH(created_at)
) AS T
ON MONTH(T.created_at) = MONTH(C.date) AND YEAR(T.created_at) = YEAR(C.date)
GROUP BY month, YEAR(created_at)
ORDER BY MONTH(date), YEAR(date)
答案 1 :(得分:0)
package mitJava2010;
public class As3_Marathon {
public static void main(String[] arguments) {
String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex", "Emma", "John", "James",
"Jane", "Emily", "Daniel", "Neda", "Aaron", "Kate" };
int[] times = { 70, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265 };
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + ": " + times[i]);
}
int f = findTheFastest(times);
int sf = find2fastest(times);
System.out.println("The fastest is " + names[f] + " with " + times[f] + " minutes");
System.out.println("The second fastest is " + names[sf] + " with " + times[sf] + " minutes");
}
private static int find2fastest(int[] times) {
int f = findTheFastest(times);
int sf = (f != 0) ? 0 : 1;
for (int i = sf + 1; i < times.length; i++) {
if (times[i] < times[sf] && i != f)
sf = i;
}
return sf;
}
private static int findTheFastest(int[] times) {
int minIn = 0;
for (int i = 1; i < times.length; i++) {
if (times[i] < times[minIn])
minIn = i;
}
return minIn;
}
}
加入具有所有记录的表将每月给您
。