簡體   English   中英

如何對一個表中的一列求和並使用另一表中的列的數據將總和分組

[英]how to sum a column from one table and group the sum using data from column of another table

我真的有一個問題,試圖總結一個表的一列,然后根據來自另一個表的數據將其分組。 他們唯一的公用密鑰是帳號。

這是場景

table 1.

account_no  volume  read_date
1            32      12016
2            22      12016
3            20      12016
4            21      12016
5            54      12016
3            65      12016
7            84      12016
8            21      12016
9            20      12016
10           30      12016

================================================== =======

table 2

account_no  Zone
1            A
2            A
3            B
4            B
5            A
3            A
7            B
8            B
9            C
10           C

結果

Zone Total
A     173
B     146
C     50

到目前為止,這就是我的查詢的方式

Select sum(volume) as Total, read_date as bDate 
GROUP BY bDate 
ORDER By bDate

它能夠基於read_date對所有卷求和,任何幫助將不勝感激...

您只需要將兩個表JOIN在一起並進行GROUP BY Zone

SELECT t2.Zone, SUM(volume) AS Total
FROM table1 AS t1
INNER JOIN table2 AS t2
ON t1.account_no = t2.account_no
GROUP BY t2.Zone

試試這個,這將基於read_dates和Zones進行總結

SELECT A.read_date
    ,B.Zone
    ,sum(A.volume) SumOfVolume
FROM @Table1 A
INNER JOIN @Table2 B ON A.account_no = B.account_no
GROUP BY A.read_date
    ,B.Zone

這可以通過使用以下命令完成:

SELECT SUM(TBL1.Volume) AS Total, TBL2.Zone
FROM TABLE1 AS TBL1
INNER JOIN TABLE2 AS TBL3
ON TBL1.Account_No = TBL2.Account_No
GROUP BY TBL2.Zone

暫無
暫無

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

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