将多列的行加在一起

时间:2019-06-24 17:36:25

标签: mysql sql

我正在尝试在表格中排列数据。该表包括以下列: 客户名称,金额,天。客户名称不是唯一的,金额是用美元表示的金额,并且一天是365天。

我试图安排每季度支付的金额,而不考虑客户的姓名。

这是一项家庭作业,我已经尝试过此代码

SELECT day as 'Quarter', SUM(amount) as 'Total Earnings'
FROM invoices
WHERE day BETWEEN 0 and 90
GROUP BY day

我遇到了3个问题。我做了上面的代码只是为了测试它在整个一年之前都能工作四分之一。

第一个问题是,我需要将“价值”这一天设置为“第一”,而且我不确定该怎么做。

其次,它总计金额,但不为0-90,总计1, 2, 3... 89, 90。而不是单行包含0-90天的总“金额”。

最后,我不确定如何为其他四分之三(91-180, 181-270, 271-365)做另一笔总和。我假设可能是子查询,但是我不确定在使用WHERE/BETWEEN时该怎么做。

我的输出应类似于:

Quarter | Total Earnings
-------------------------
First   | 111111111
Second  | 111111111
Third   | 111111111
Fourth  | 111111111

3 个答案:

答案 0 :(得分:2)

SELECT 'first' AS quarter, SUM(amount) AS total_earnings
FROM invoices where day between 0 AND 90
UNION ALL
SELECT 'second' AS quarter, SUM(amount) AS total_earnings
FROM invoices where day between 91 AND 180
UNION ALL
SELECT 'third' AS quarter, SUM(amount) AS total_earnings
FROM invoices where day between 181 AND 270
UNION ALL
SELECT 'fourth' AS quarter, SUM(amount) AS total_earnings
FROM invoices where day >= 271 

这将为您带来预期的结果。与四分之一不同,您使用的分组将尝试根据天分组

答案 1 :(得分:0)

您可以使用CASE来查找一天中的哪个季度,然后按该季度分组。像这样:

 SELECT `quarter` AS 'Quarter',
        SUM(amount) AS 'Total Earnings'
   FROM (
      SELECT CASE WHEN DAY < (365/4)
                  THEN 'First'
                  WHEN t.`day` < (365/4)*2
                  THEN 'Second'
                  WHEN t.`day` < (365/4)*3
                  THEN 'Third'
                  ELSE 'Fourth'
              END AS `quarter`,
              t.* 
         FROM `table` t
         ) t2
GROUP BY `quarter`;

您当然可以仅用几天的时间替换365 /,或者为一年中的天数设置一个变量,例如SET @days_in_year = 365;。我只是手动计算,以快速解释数字是什么。

答案 2 :(得分:0)

使用CASE语句,您可以评估Quarter,然后可以group by Quarter

SELECT 
  case 
    when day BETWEEN 0 and 90 then 'First'
    when day BETWEEN 91 and 180 then 'Second'
    when day BETWEEN 181 and 270 then 'Third'
    else 'Fourth'
  end Quarter, 
  SUM(amount) as `Total Earnings`
FROM invoices
GROUP BY Quarter

根据需要更改日期范围。