Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL查询以统计记录_Sql_Sql Server_Database_Sql Server 2008 - Fatal编程技术网

SQL查询以统计记录

SQL查询以统计记录,sql,sql-server,database,sql-server-2008,Sql,Sql Server,Database,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.

我正在创建一个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
交易类型表仅包含所有交易类型,交易数据包含已发生的交易

我面临的问题是,即使它是正确的联接,它也不会从事务类型表中选择所有记录

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

请帮忙。

左键连接更容易理解

我想你想要:

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;
注:

使用合理的表别名!a和b毫无意义。t和tt是表名的缩写,因此更容易理解。 t、 对于不匹配的行,模式将为NULL。 日期条件必须在on条款中。否则,外部联接将变为内部联接。 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;
注:

使用合理的表别名!a和b毫无意义。t和tt是表名的缩写,因此更容易理解。 t、 对于不匹配的行,模式将为NULL。 日期条件必须在on条款中。否则,外部联接将变为内部联接。 LEFT JOIN更容易理解,至少对于母语从左到右阅读的人来说是这样,因为它意味着保留表中已阅读的所有行。
按从组中删除trxType。通常按所选列分组,但作为设置函数参数的列除外。请按从分组中删除trxType。您通常按所选的列进行分组,但设置函数的参数除外。是否有一种方法可以为所有事务类型选择t.mode?请您对此稍加说明?@Talib。不,您不能为不匹配的行选择值。是否有一种方法可以为所有交易类型选择t.mode?请您对此稍加说明?@Talib。否,不能为不匹配的行选择值。