2012-01-09 205 views
3

我有一个查询返回644行,按几列分组。我需要得到这些行的计数,644GROUP BY的COUNT(*)

这是查询:

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 

尽管试图COUNT(*),在另一个查询包裹,并取出GROUP BY,我不能让“644”背部。我最近来的是644行,全都包含'1'。这可能吗?

+0

'select count(1)from(select distinct ID, honame,来自HeadOffice的ho_status)忽略'return? – dasblinkenlight 2012-01-09 16:03:26

+0

如果您的原始查询返回正确的行数,您为什么要在从(<您的原始查询>)中选择计数(*)时进行更改? – JeffO 2012-01-09 16:15:24

回答

4

最简单的方式做到这一点正是如此:

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 

如果你想计数加你的专栏,使用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 
+1

我正在做COUNT(*)从上面,但这完美的作品。谢谢。 – Echilon 2012-01-09 16:12:33

2

您将得到1个更多的行到您的列表中,其中包含属性数量和属性值的所有内容的空值。该记录将具有计数和所有属性值的总和。

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 Grouping sets((ho.ID,ho.honame,ho_status),()) 
ORDER BY ho_status 
0

这应该工作

SELECT COUNT(ID) 
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) t