Mysql根据条件计算列值

时间:2017-05-22 06:05:43

标签: mysql count conditional-statements

我有一个包含"private": true, "scripts": { "postinstall": "./postinstall.sh \"$NODE_ENV\"" } daymonthyear列的表格。我必须根据total_paymentstotal_paymentsdays计算months

如何计算值?

我在想代码:

years

但它不会返回正确的答案。我想逐日,按月,按年计算select month, year, sum(total_payments) from webassignment.subscription_stats group by day; select month, year, sum(total_payments) from webassignment.subscription_stats group by month; select month, year, sum(total_payments) from webassignment.subscription_stats group by year; 。请帮我找到价值观。

示例输入:

total_payments

输出:

Daywise:

Day Month   Year    Total_payments
10  01      2008    10
10  01      2008    20
11  02      2008    10
10  03      2010    10

月份和年份相同

2 个答案:

答案 0 :(得分:0)

一种方法可能是在联盟上使用,以显示基于不同级别的不同结果

  select day, month,year,sum(total_payments) 
  from webassignment.subscription_stats group by day, month,year
  union 
  select null, month,year,sum(total_payments) 
  from webassignment.subscription_stats group by month,year
  union 
  select null, null ,year,sum(total_payments) 
  from webassignment.subscription_stats group by year
  order by year, month, day

您提供的样本应该足够了

  select day, month,year,sum(total_payments) 
  from webassignment.subscription_stats group by day, month,year
  order by day, month,year

答案 1 :(得分:0)

您可以使用GROUP BY WITH ROLLUP按年,月和日获得总计摘要:

SELECT
    `Year`,
    `Month`,
    `Day`,
    SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
GROUP BY `Year`,`Month`,`Day` WITH ROLLUP;

如果您想要年,月和日的个人查询:

按年份:

SELECT
    `Year`,
    SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
GROUP BY `Year`
ORDER BY `Year;

按月:

SELECT
    `Year`,
    `Month`,
    SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
WHERE `Year` = 2017
GROUP BY `Year`,`Month`
ORDER BY `Year`,`Month`;

白天:

SELECT
    `Year`,
    `Month`,
    `Day`,
    SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
GROUP BY `Year`,`Month`,`Day`
ORDER BY `Year`,`Month`,`Day`;