SQL Server Count on a grouped by

感情迁移 提交于 2019-12-12 12:20:28

问题


I got 3 tables. I want to group by the item.name and count the times it can be found in idetail. This query only counts all rows not the grouped by rows.

Anyone knows how to fix it?

SELECT i.name, COUNT(i.name)
FROM item AS i
INNER JOIN item_category AS ic ON i.i_category_id = ic.ic_id
INNER JOIN idetail AS id ON ic.ic_id = id.id_category_id
WHERE ic.ic_id = 1002
GROUP BY i.name

回答1:


This is what you want:

select x.name
     , count(*) as cntNames
     , sum(x.cntDetails) as cntDetails
  from (
        SELECT i.name, COUNT(*) as cntDetails
          FROM item AS i
         INNER JOIN item_category AS ic ON i.i_category_id = ic.ic_id
         INNER JOIN idetail AS id ON ic.ic_id = id.id_category_id
         WHERE ic.ic_id = 1002
          -- NOTICE THE 2nd Value in the group by!
         GROUP BY i.name,id.id_category_id
       ) x
  group by name



回答2:


Select  Count(*)
From    (
            Select i.name, Count(i.name)
            From item As I
                Join item_category As ic
                    On ic.ic_id = i.category_id
                Join idetail as ID
                    On ID.id_category_id = ic.ic_id
            Where ic.ic_id = 1002
            Group By i.name
            ) As Z

If you want all three columns and you are using SQL Server 2005+

With Items As
    (
    Select I.name, Count(i.name) As ItemCount
    From item As I
        Join item_category As ic
            On ic.ic_id = i.category_id
        Join idetail as ID
            On ID.id_category_id = ic.ic_id
    Where ic.ic_id = 1002
    Group By i.name
    )
Select Name, ItemCount
    ,   (
        Select Count(*)
        From Items
        ) As OverallCount
From Items  

Another simpler version if you are using SQL Server 2005+.

Select i.name
    , Count(i.name) As CountByName
    , Count(*) Over() As TotalCount
From item As I
    Join item_category As ic
        On ic.ic_id = i.category_id
    Join idetail as ID
        On ID.id_category_id = ic.ic_id
Where ic.ic_id = 1002
Group By i.name


来源:https://stackoverflow.com/questions/4700155/sql-server-count-on-a-grouped-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!