简体   繁体   English

SQL查询计数记录

[英]SQL Query to count the records

I am making up a SQL query which will get all the transaction types from one table, and from the other table it will count the frequency of that transaction type. 我正在组成一个SQL查询,它将从一个表中获取所有事务类型,而从另一个表中将计算该事务类型的频率。

My query is this: 我的查询是这样的:

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

The transaction_types table contains all the types of transactions only and transaction_data contains the transactions which have occurred. transaction_types表仅包含所有交易类型, transaction_data包含已发生的交易。

The problem I am facing is that even though it's the RIGHT join , it does not select all the records from the transaction_types table. 我面临的问题是,即使它是RIGHT join ,它也不会从transaction_types表中选择所有记录。

I need to select all the transactions from the transaction_types table and show the number of counts for each transaction, even if it's 0. 我需要从transaction_types表中选择所有事务,并显示每个事务的计数数量,即使它是0。

Please help. 请帮忙。

LEFT JOIN is so much easier to follow. LEFT JOIN非常容易遵循。

I think you want: 我想你要:

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;

Notes: 笔记:

  • Use reasonable table aliases! 使用合理的表别名! a and b mean nothing. ab毫无意义。 t and tt are abbreviations of the table name, so they are easier to follow. ttt是表名的缩写,因此更易于遵循。
  • t.mode will be NULL for non-matching rows. 对于不匹配的行, t.mode将为NULL
  • The condition on dates needs to be in the ON clause. 日期条件必须在ON子句中。 Otherwise, the outer join is turned into an inner join. 否则,外部联接将变为内部联接。
  • LEFT JOIN is easier to follow (at least for people whose native language reads left-to-right) because it means "keep all the rows in the table you have already read". LEFT JOIN更容易遵循(至少对于母语从左到右阅读的人而言),因为它的意思是“保留已读表中的所有行”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM