2012-01-09 250 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