How do I use T-SQL Group By

后端 未结 5 1504
星月不相逢
星月不相逢 2020-12-06 04:17

I know I need to have (although I don\'t know why) a GROUP BY clause on the end of a SQL query that uses any aggregate functions like count,

5条回答
  •  执笔经年
    2020-12-06 04:59

    GROUP BY is similar to DISTINCT in that it groups multiple records into one.

    This example, borrowed from http://www.devguru.com/technologies/t-sql/7080.asp, lists distinct products in the Products table.

    SELECT Product FROM Products GROUP BY Product
    
    Product
    -------------
    Desktop
    Laptop
    Mouse
    Network Card
    Hard Drive
    Software
    Book
    Accessory
    

    The advantage of GROUP BY over DISTINCT, is that it can give you granular control when used with a HAVING clause.

    SELECT Product, count(Product) as ProdCnt
    FROM Products
    GROUP BY Product
    HAVING count(Product) > 2
    
    Product      ProdCnt
    --------------------
    Desktop          10
    Laptop            5
    Mouse             3
    Network Card      9
    Software          6
    

提交回复
热议问题