SQL按月和月汇总交易

时间:2018-11-05 16:18:09

标签: sql sql-server

我正在尝试汇总某些项目的总额。例如,我想获取trx_desc为“ Amazon”且在八月份的所有交易的总金额。

这是我用来尝试输出此数据的查询:

select det_trx_type, SUM(amount) as 'Total Amt',
CASE
    when MONTH(posting_date) = 8 THEN 'August'
    when MONTH(posting_date) = 9 THEN 'September'
    when MONTH(posting_date) = 10 THEN 'October'
END
as 'Month'

from av_finance 
where det_trx_type IN(
select distinct det_trx_type from av_finance)
group by  posting_date, det_trx_type

查询数据

我希望在给定月份中,每笔购买的8月份的亚马逊购买总数显示为1行,而不是多行。

3 个答案:

答案 0 :(得分:0)

您可以尝试将CASE WHEN分组,而不是仅将posting_date列作为分组依据,因为posting_date似乎是日期数据类型。

select det_trx_type, SUM(amount) as 'Total Amt',
CASE
    when MONTH(posting_date) = 8 THEN 'August'
    when MONTH(posting_date) = 9 THEN 'September'
    when MONTH(posting_date) = 10 THEN 'October'
END as 'Month'
from av_finance 
where det_trx_type IN(select distinct det_trx_type from av_finance)
group by  
CASE
    when MONTH(posting_date) = 8 THEN 'August'
    when MONTH(posting_date) = 9 THEN 'September'
    when MONTH(posting_date) = 10 THEN 'October'
END, det_trx_type

答案 1 :(得分:0)

我认为您可以尝试通过这种方式进行汇总:

select det_trx_type, SUM(amount) as 'Total Amt',
    CASE
        when MONTH(posting_date) = 8 THEN 'August'
        when MONTH(posting_date) = 9 THEN 'September'
        when MONTH(posting_date) = 10 THEN 'October'
    END
    as 'Month'

    from av_finance 
    where det_trx_type IN(
    select distinct det_trx_type from av_finance)
    group by  MONTH(posting_date), det_trx_type

答案 2 :(得分:0)

停止按posting_date分组,也按CASE表达式分组(或在CTE或子查询中派生)。这是CTE示例:

;WITH x AS
(
  select det_trx_type, amount,
  CASE
    when MONTH(posting_date) = 8 THEN 'August'
    when MONTH(posting_date) = 9 THEN 'September'
    when MONTH(posting_date) = 10 THEN 'October'
  END as [Month] -- don't use ' for aliases!
  from dbo.av_finance  -- always use schema!
)
SELECT [Month], det_trx_type, SUM(amount)
FROM x
GROUP BY [Month], det_trx_type;

我还删除了where in ... distinct子句。我不确定它的作用是什么。