我试图使用mysql通过house_details表中的subincome字段显示progressive_total和cumulative_sum组。我在 link
中构建了我的架构工作查询:
SELECT *,
COALESCE(
(SELECT SUM(x.rupees)
FROM house_details x
WHERE MONTH(x.date) < t1.month), '-') AS progressive_total,
(SELECT SUM(x.rupees)
FROM house_details x
WHERE MONTH(x.date) <= t1.month) AS cumulative_sum
FROM
(SELECT MONTHNAME(t.date) AS `monthname`,
MONTH(t.date) `month`,
YEAR(t.date) AS YEAR,
t.income,
t.subincome,
t.ssubincome,
SUM(rupees) AS amount,
GROUP_CONCAT(receipt_id) AS receipt_ids
FROM house_details t
WHERE YEAR(t.date) = YEAR(CURRENT_DATE())
GROUP BY month(t.date),
t.subincome
ORDER BY t.date) t1
但这会在字段中显示无关的cumulative_sum。
我尝试在子查询中使用group,如下所示:
查询:
SELECT *,
COALESCE(
(SELECT SUM(x.rupees)
FROM house_details x
WHERE MONTH(x.date) < t1.month
GROUP BY x.subincome), '-') AS progressive_total,
(SELECT SUM(x.rupees)
FROM house_details x
WHERE MONTH(x.date) <= t1.month
GROUP BY x.subincome) AS cumulative_sum
FROM
(SELECT MONTHNAME(t.date) AS `monthname`,
MONTH(t.date) `month`,
YEAR(t.date) AS YEAR,
t.income,
t.subincome,
t.ssubincome,
SUM(rupees) AS amount,
GROUP_CONCAT(receipt_id) AS receipt_ids
FROM house_details t
WHERE YEAR(t.date) = YEAR(CURRENT_DATE())
GROUP BY month(t.date),
t.subincome
ORDER BY t.date) t1;
但它显示错误子查询返回多行。
答案 0 :(得分:1)
在&#34; FROM&#34;的前一部分中写入的子查询必须只返回一行。显然,你的查询在这里转了多行。
此外,查询似乎有点复杂。 您可以轻松获得这样的累进总和:
import java.io.BufferedReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
String myBeautifulScanf = new Scanner(System.in).nextLine();
System.out.println( myBeautifulScanf );
}
}
你可以按照这个想法分组:
每月分组
set @csum := 0;
select id, date, rupees ,(@csum := @csum + rupees) as proggressive_sum
from house_details
order by date;
分组年度和次级分组:
set @csum := 0;
select month,sum_rupees, (@csum := @csum + sum_rupees) as progressive_sum_monthly
from (
select DATE_FORMAT(date,'%Y-%m') month, sum(rupees) sum_rupees
from house_details
GROUP BY DATE_FORMAT(date,'%Y-%m')
) gg
order by 1;
答案 1 :(得分:1)
您可以使用以下查询来获得预期的结果集
SELECT *,
COALESCE(
(SELECT SUM(pt.rupees) FROM (
SELECT MONTH(`date`) `month`,
MAX(id) id,
SUM(rupees) rupees
FROM house_details
GROUP BY `month`,subincome
) pt
WHERE CASE WHEN pt.month = t1.month THEN pt.id < t1.id ELSE pt.month < t1.month END
), 0) AS progressive_total,
(SELECT SUM(rupees) FROM(
SELECT MONTH(`date`) `month`,
MAX(id) id,
SUM(rupees) rupees
FROM house_details
GROUP BY `month`,subincome
) cs
WHERE CASE WHEN cs.month = t1.month THEN cs.id <= t1.id ELSE cs.month <= t1.month END
) AS cumulative_sum
FROM (
SELECT MONTHNAME(t.date) AS `monthname`,
MAX(id) id,
MONTH(t.date) `month`,
YEAR(t.date) AS `year`,
GROUP_CONCAT(t.income) income,
t.subincome,
GROUP_CONCAT(t.ssubincome) ssubincome,
SUM(rupees) AS amount,
GROUP_CONCAT(receipt_id) AS receipt_ids
FROM house_details t
WHERE YEAR(t.date) = YEAR(CURRENT_DATE())
GROUP BY `monthname`,`month`, t.subincome
ORDER BY `month`
) t1