SQL Query来计算记录

Tal*_*lib 0 sql database sql-server sql-server-2008

我正在编写一个SQL查询,它将从一个表中获取所有事务类型,而从另一个表中,它将计算该事务类型的频率.

我的查询是这样的:

with CTE as
(
select a.trxType,a.created,b.transaction_key,b.description,a.mode
FROM transaction_data AS a with (nolock)
     RIGHT JOIN transaction_types b with (nolock) ON b.transaction_key = a.trxType 
 )
SELECT COUNT (trxType) AS Frequency, description as trxType,mode
from CTE where created >='2017-04-11' and created <= '2018-04-13'
group by trxType ,description,mode
Run Code Online (Sandbox Code Playgroud)

transaction_types表仅包含所有类型的事务,并transaction_data包含已发生的事务.

我面临的问题是即使它是RIGHT join,它也不会从transaction_types表中选择所有记录.

我需要从transaction_types表中选择所有事务并显示每个事务的计数数,即使它为0.

请帮忙.

Gor*_*off 6

LEFT JOIN 更容易遵循.

我想你想要:

select tt.transaction_key, tt.description, t.mode, count(t.trxType)
from transaction_types tt left join
     transaction_data t
     on tt.transaction_key = t.trxType and
        t.created >= '2017-04-11' and t.created <= '2018-04-13'
group by tt.transaction_key, tt.description, t.mode;
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 使用合理的表别名! ab没有任何意义. t并且tt是表名的缩写,因此它们更容易遵循.
  • t.modeNULL用于不匹配的行.
  • 日期的条件需要在ON条款中.否则,外部联接将变为内部联接.
  • LEFT JOIN 更容易理解(至少对于母语从左到右阅读的人),因为它意味着"保留已经阅读的表格中的所有行".