SQL 查询 - 添加汇总行

SQL query - add summary row

我正在尝试为我的 gradana sqlite 查询添加摘要行。

我现在的查询是这样的:

SELECT
date(close_date) AS "Date",
(SELECT COUNT(*) FROM trades WHERE close_profit > 0 AND date(c2.close_date) = date(close_date)) AS Wins,
(SELECT COUNT(*) FROM trades WHERE close_profit < 0 AND date(c2.close_date) = date(close_date)) AS Losses,
(SELECT AVG(close_profit * 100) FROM trades WHERE date(c2.close_date) = date(close_date)) AS "Avg",
(SELECT SUM(close_profit_abs) FROM trades WHERE date(c2.close_date) = date(close_date)) AS "Profit"
FROM trades c2 WHERE date(close_date) IS NOT NULL GROUP BY date(close_date) ORDER BY Date DESC

它输出 table 像这样:

Date         Wins      Losses      Avg     Profit
2021-09-23      1           0        3       68.8
2021-09-22      2           0      1.7       78.7
2021-09-21      5           0      4.8        538
2021-09-20     14           0      1.7        445

如何向 table 添加摘要行? 像这样:

Date         Wins      Losses      Avg     Profit
Total          22           0      2.8     1130.5   
2021-09-23      1           0        3       68.8
2021-09-22      2           0      1.7       78.7
2021-09-21      5           0      4.8        538
2021-09-20     14           0      1.7        445

摘要行应该是第一行。 胜利是所有胜利的总和。 损失是所有损失的总和。 Avg 是所有 Avg 的平均值。 利润是所有利润的总和。

我试过这样的事情:

SELECT
  [close_date] = COALESCE(close_date, 'Total') AS date,
  [close_profit_abs] = SUM(close_profit_abs),
(SELECT COUNT(*) FROM trades WHERE close_profit > 0 AND date(c2.close_date) = date(close_date)) AS Wins,
(SELECT COUNT(*) FROM trades WHERE close_profit < 0 AND date(c2.close_date) = date(close_date)) AS Losses,
(SELECT AVG(close_profit * 100) FROM trades WHERE date(c2.close_date) = date(close_date)) AS "Avg",
(SELECT SUM(close_profit_abs) FROM trades WHERE date(c2.close_date) = date(close_date)) AS "Profit"
FROM trades c2 WHERE date(close_date) IS NOT NULL GROUP BY date(close_date) ORDER BY Date DESC

但这一切都被搞砸了..我的 sql 技能还不够.. 谁能帮我这个 ?我可以找到更简单的指南,当我尝试将它们实现到我现有的代码时,一切都会变得混乱。

感谢任何帮助.. Thx

你可以这样做 ('summary row' UNION ALL 'your query'):

我改进了你的查询(我去掉了你的子查询),如果结果不正确请告诉我。

SELECT *
FROM (

    SELECT 
           'Total' AS "Date",
           count(CASE WHEN close_profit > 0 THEN 1 END) AS Wins,
           count(CASE WHEN close_profit < 0 THEN 1 END) AS Losses,
           AVG(close_profit * 100) AS "Avg",
           SUM(close_profit_abs)  AS "Profit"
    FROM trades
    WHERE close_date IS NOT NULL 

    UNION ALL

    SELECT
           date(close_date) AS "Date",
           count(CASE WHEN close_profit > 0 THEN 1 END) AS Wins,
           count(CASE WHEN close_profit < 0 THEN 1 END) AS Losses,
           AVG(close_profit * 100) AS "Avg",
           SUM(close_profit_abs)  AS "Profit"
    FROM trades
    WHERE close_date IS NOT NULL 
    GROUP BY date(close_date)) AS sq

ORDER BY "Date" DESC;