计算多个条件的记录

时间:2018-04-24 12:50:51

标签: sql sql-server sql-server-2008

我的查询是计算表中发生的事务数。以下是我的询问:

select tt.transaction_key, tt.description, t.mode, count(t.TransactionType) as Frequency
from transaction_names tt left join
     transaction_report_data t
     on tt.transaction_key = t.TransactionType and
        t.created >='2017-04-11' and t.created <= '2018-04-13'
group by tt.transaction_key, tt.description, t.mode;

我还需要只有成功或者t.status ='成功'的交易数量的计数/频率。

请帮助我如何调整此'where'子句以计算此类记录。

提前致谢。

3 个答案:

答案 0 :(得分:2)

你可以使用下面的聚合

来做一个案例
select 
tt.transaction_key, 
tt.description, 
t.mode, 
count(t.TransactionType) as Frequency,
Sum(case when t.status='success' then 1 else 0 end) as SuccessfulTransactions
from transaction_names tt left join
     transaction_report_data t
     on tt.transaction_key = t.TransactionType and
        t.created >='2017-04-11' and t.created <= '2018-04-13'
group by tt.transaction_key, tt.description, t.mode;

答案 1 :(得分:1)

试试这个

SELECT
    tt.transaction_key,
    tt.[Description],
    t.mode,
    COUNT(t.TransactionType) AS Frequency,
    Success = SUM(CASE WHEN T.[Status]='Success' THEN 1 ELSE 0 END)
    FROM transaction_names tt
       LEFT JOIN transaction_report_data t 
          ON tt.transaction_key = t.TransactionType
             AND t.created >= '2017-04-11'
             AND t.created <= '2018-04-13'
       GROUP BY 
          tt.transaction_key,
          tt.[Description],
          t.mode;

答案 2 :(得分:0)

select tt.transaction_key, tt.description, t.mode, count(t.TransactionType) as Frequency
from transaction_names tt left join
     transaction_report_data t
     on tt.transaction_key = t.TransactionType and
        t.created >='2017-04-11' and t.created <= '2018-04-13'
group by tt.transaction_key, tt.description, t.mode, t.status
having t.status = 'success'