【问题标题】:COUNT(*) of GROUP BYGROUP BY 的 COUNT(*)
【发布时间】:2012-01-09 15:55:25
【问题描述】:

我有一个查询,它返回 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”。这可能吗?

【问题讨论】:

  • select count(1) from (select distinct ID, honame, ho_status from HeadOffice) ignore 返回什么?
  • 如果您的原始查询返回正确的行数,为什么要在 Select count(*) from () 中换行时更改它?

标签: sql sql-server sql-server-2008 count group-by


【解决方案1】:

这样做的简单方法是:

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

【讨论】:

  • 我在上面做 COUNT(*) ,但这很有效。谢谢。
【解决方案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

【讨论】:

    【解决方案3】:

    这应该可以工作

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 2012-05-06
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 2014-05-20
      相关资源
      最近更新 更多