我有一个返回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
尽管尝试COUNT(*)
,将其包装在另一个查询中并删除GROUP BY
,我仍然无法获得'644'。我最接近的是644行,都包含'1'。这可能吗?
答案 0 :(得分: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 :(得分: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
答案 2 :(得分: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