按月求和和计数,显示当月的最后一天

rryofs0p  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(335)

我有这样一个事务表:

Trandate    channelID   branch    amount
---------   ---------   ------    ------
01/05/2019     1          2        2000
11/05/2019     1          2        2200
09/03/2020     1          2        5600
15/03/2020     1          2        600
12/10/2019     2         10        12000
12/10/2019     2         10        12000
15/11/2019     4          7        4400
15/02/2020     4          2        2500

我需要按年度和月份计算金额和交易数量。我试过这个:

select DISTINCT 
   DATEPART(YEAR,a.TranDate) as [YearT],
   DATEPART(MONTH,a.TranDate) as [monthT],
   count(*) as [countoftran], 
   sum(a.Amount) as [amount], 
   a.Name as [branch], 
   a.ChannelName as [channelID] 
from transactions as a
where a.TranDate>'20181231' 
group by a.Name, a.ChannelName, DATEPART(YEAR,a.TranDate), DATEPART(MONTH,a.TranDate) 
order by a.Name, YearT, MonthT

就像魅力一样。但是,我将在powerbi上使用这些数据,因此我无法在“线图”中显示这些结果,因为年份和月份信息在不同的列中。
我试着把sql的格式改成 'YYYYMM' 可惜powerbi没有将此列识别为日期。
最后,我需要一个如下的结果表:

YearT      channelID   branch    Tamount   TranT
---------   ---------   ------    -------   -----
31/05/2019     1          2        4400      2
30/03/2020     1          2        7800      2
31/10/2019     2         10        24000     2
30/11/2019     4          7        4400      1
29/02/2020     4          2        2500      1

我试过几次小小的改变,都没有结果。
非常感谢你的帮助。

t1qtbnec

t1qtbnec1#

您可以尝试使用以下语句:

SELECT 
   EOMONTH(DATEFROMPARTS(YEAR(Trandate), MONTH(Trandate), 1)) AS YearT,
   branch, channelID,
   SUM(amount) AS TAmount,
   COUNT(*) AS TranT
FROM (VALUES
   ('20190501', 1,  2, 2000),
   ('20190511', 1,  2, 2200),
   ('20200309', 1,  2, 5600),
   ('20200315', 1,  2, 600),
   ('20191012', 2, 10, 12000),
   ('20191012', 2, 10, 12000),
   ('20191115', 4,  7, 4400),
   ('20200215', 4,  2, 2500)
) v (Trandate, channelID, branch, amount)
GROUP BY DATEFROMPARTS(YEAR(Trandate), MONTH(Trandate), 1), branch, channelID
ORDER BY DATEFROMPARTS(YEAR(Trandate), MONTH(Trandate), 1)

结果:

YearT       branch  channelID   TAmount TranT
2019-05-31  2       1           4200    2
2019-10-31  10      2           24000   2
2019-11-30  7       4           4400    1
2020-02-29  2       4           2500    1
2020-03-31  2       1           6200    2

相关问题