簡體   English   中英

跨多個列的sql sum()

[英]sql sum() across multiple columns

我有一個包含7列的表格:

Color1 (string)
Color2 (string)
Color3 (string)
Use1 (decimal)
Use2 (decimal)
Use3 (decimal)
Date


Col1  |  Col2  |  Col3 |  Use1  |  Use2  |  Use3  |  Date
---------------------------------------------------------------
Red   |  Green |  Red  |  2     |   6    |  8     |  30-01-2018
Red   |  Black |  Black|  5     |   7    |  9     |  25-02-2019
Green |  Red   |  Green|  1     |   3    |  3     |  30-05-2019

我需要將所有顏色和使用情況匯總到一個列表中:

Color  |  Month  |  Usage  |
----------------------------
Red    |    01   |   10    |
Red    |    02   |    5    |
Red    |    05   |    3    |
Green  |    01   |    6    |
Green  |    05   |    4    |
Black  |    02   |    16   |

努力尋找一種用SQL進行此操作的方法。...如果有人可以幫助我解決這個問題,我將非常感激。

一種方法是union all 確切的語法可能因數據庫而異,但是其思想是:

select color, month, sum(usage)
from ((select col1 as color, month(date) as month, (use1 + use2 + use3) as usage
      from t
      ) union all
      (select col1 as color, month(date) as month, (use1 + use2 + use3) as usage
       from t
      ) union all
      (select col1 as color, month(date) as month, (use1 + use2 + use3) as usage
       from t
      )
     )
group by color, month;

通過summing up子查詢內部和外部的使用情況與整個數據重復顏色幾個月的概率(在此可能不會在此處共享) summing up分別考慮每個coluse情況。

select color, month, sum(usage) as usage
  from
  (
   select col1 as color, extract(month from Date) as month, 
         sum(use1) as usage from tab group by col1, extract(month from Date) union all
   select col2, extract(month from Date), 
         sum(use2) from tab group by col2, extract(month from Date) union all
   select col3, extract(month from Date), 
         sum(use3) from tab group by col3, extract(month from Date)
  ) q
 group by color, month;

順便說一下,我們對DBMS並不了解。 OracleMySQLPostgres支持extract()函數。

我認為這是一個有趣的問題,可以嘗試一下t-sql。 不幸的是,unpivot無法將顏色和用法分為兩列,因此我將顏色和用法合並為nvarchar。 不幸的是,這並不理想。 但也許它給其他人一些想法。

select date, col 
from (select mth, col1_use1 = colour1+convert(nvarchar, usage1)
           , col2_use2 = colour2+convert(nvarchar, usage2)
           , col3_use3 = colour3+convert(nvarchar, usage3)
        from colourusagemonth)  m
unpivot 
    (col for colour in (col1_use1, col2_use2, col3_use3) 
    ) as unpvt;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM