计算由组返回的logging数

如何计算查询返回的logging数量,

例如:

select count(*) from temptable group by column_1, column_2, column_3, column_4 

给我,

 1 1 2 

我需要计算上面的logging得到1 + 1 + 1 = 3。

你可以在一个查询中使用另一个COUNT上的OVER子句

 select count(*) RecordsPerGroup, COUNT(*) OVER () AS TotalRecords from temptable group by column_1, column_2, column_3, column_4 

最简单的解决scheme是使用派生表:

 Select Count(*) From ( Select ... From TempTable Group By column_1, column_2, column_3, column_4 ) As Z 

另一个解决scheme是使用计数差异:

 Select ... , ( Select Count( Distinct column_1, column_2, column_3, column_4 ) From TempTable ) As CountOfItems From TempTable Group By column_1, column_2, column_3, column_4 

我知道这是相当晚,但没有人提出这样的build议:

 select count ( distinct column_1, column_2, column_3, column_4) from temptable 

这至less在Oracle中起作用 – 我目前还没有其他数据库来testing它,而且我对T-Sql和MySQL语法也不太熟悉。

另外,我还不完全确定parsing器是否更有效率地执行此操作,或者是否其他人的嵌套select语句的解决scheme更好。 但是从编码的angular度来看,我觉得这个更优雅。

我试图达到没有子查询,并能够得到所需的结果如下

 SELECT DISTINCT COUNT(*) OVER () AS TotalRecords FROM temptable GROUP BY column_1, column_2, column_3, column_4 

CTE为我工作:

 with cte as ( select 1 col1 from temptable group by column_1 ) select COUNT(col1) from cte; 

你可以这样做:

 select sum(counts) total_records from ( select count(*) as counts from temptable group by column_1, column_2, column_3, column_4 ) as tmp 

在PostgreSQL中,这对我有用:

 select count(count.counts) from (select count(*) as counts from table group by concept) as count; 

你能执行下面的代码吗? 它在Oracle中工作。

 SELECT COUNT(COUNT(*)) FROM temptable GROUP BY column_1, column_2, column_3, column_4 

怎么样:

 SELECT count(column_1) FROM (SELECT * FROM temptable GROUP BY column_1, column_2, column_3, column_4) 

你也可以通过下面的查询得到

 select column_group_by,count(*) as Coulm_name_to_be_displayed from Table group by Column; -- For example: select city,count(*) AS Count from people group by city 

试试这个查询:

 select top 1 TotalRows = count(*) over () from yourTable group by column1, column2 

如何在SQL Server中使用COUNT OVER(PARTITION BY {按列分组})分区函数?

例如,如果要按ItemID对产品销售进行分组,并且您希望计算每个不同的ItemID,则只需使用:

 SELECT {columns you want} , COUNT(ItemID) OVER (PARTITION BY ItemID) as BandedItemCount , {more columns you want}... , FROM {MyTable} 

如果你使用这种方法,你可以把GROUP BY放在图片外面 – 假设你想返回整个列表(你可以做一些报告,你需要知道整个项目的计数,显示整个数据集,即Reporting Services)。