COUNT(*)GROUP BY

Ech*_*lon 4 sql sql-server group-by count sql-server-2008

我有一个查询,该查询返回644行,按几列分组。我需要对这些行进行计数644。

这是查询:

SELECT DISTINCT ho.ID,ho.honame,ho.ho_status,SUM(Properties.Value) as [sales value], COUNT(Properties.record_id) as [property count]
FROM HeadOffice ho INNER JOIN Properties ON Properties.head_office_code = ho.id
WHERE Somecondition
GROUP BY ho.ID,ho.honame,ho_status ORDER BY ho_status
Run Code Online (Sandbox Code Playgroud)

尽管尝试过COUNT(*),将其包装在另一个查询中并删除了GROUP BY,但我无法返回“ 644”。我最接近的是644行,所有行都包含“ 1”。这可能吗?

Eri*_*ric 5

因此,简单的方法是:

SELECT count(1) as NumRows from
(SELECT DISTINCT ho.ID,ho.honame,ho.ho_status,SUM(Properties.Value) as [sales value], COUNT(Properties.record_id) as [property count]
FROM HeadOffice ho INNER JOIN Properties ON clients.head_office_code = ho.id
WHERE Somecondition
GROUP BY ho.ID,ho.honame,ho_status ORDER BY ho_status) x
Run Code Online (Sandbox Code Playgroud)

如果需要计数加列,请使用over

SELECT 
    count(1) over () as NumRows,
    x.ID,
    x.ho_status,
    x.[sales value],
    x.[property count]
from
(SELECT DISTINCT ho.ID,ho.honame,ho.ho_status,SUM(Properties.Value) as [sales value], COUNT(Properties.record_id) as [property count]
FROM HeadOffice ho INNER JOIN Properties ON clients.head_office_code = ho.id
WHERE Somecondition
GROUP BY ho.ID,ho.honame,ho_status ORDER BY ho_status) x
Run Code Online (Sandbox Code Playgroud)