如何在SQL Server中获取所有数据以及Group BY Count

时间:2015-06-17 16:09:12

标签: sql sql-server sql-server-2008

所以我有ID,CustomerID,Name,Salary

的表

我希望数据返回的方式是使用新列的所有数据,按客户ID显示记录组总数

 ID        CustomerID    Name    Salary
  1            1          John    3000
  2            1          Kim     1000
  3            2          Sarah   2000
  4            2          Jim     4000
  5            2          Kane    2000 
  6            3          Bul     2500

所以我想要这样的东西,新的列以记录的总数显示组,

  ID        CustomerID    Name    Salary   Count
  1            1          John    3000       2
  2            1          Kim     1000       2
  3            2          Sarah   2000       3
  4            2          Jim     4000       3
  5            2          Kane    2000       3
  6            3          Bul     2500       1

4 个答案:

答案 0 :(得分:5)

您正在寻找窗口函数,在本例中为count()

select t.*, count(*) over (partition by CustomerId) as cnt
from table t;

答案 1 :(得分:0)

select 
ID,CustomerID,Name,Salary, COUNT(CustomerID) Count
from tableName
group by ID,CustomerID,Name,Salary

答案 2 :(得分:0)

您可以加入计算计数的子查询:

CREATE TABLE #customer
    (
      [ID] INT ,
      [CustomerID] INT ,
      [Name] VARCHAR(5) ,
      [Salary] INT
    );

INSERT  INTO #customer
        ( [ID], [CustomerID], [Name], [Salary] )
VALUES  ( 1, 1, 'John', 3000 ),
        ( 2, 1, 'Kim', 1000 ),
        ( 3, 2, 'Sarah', 2000 ),
        ( 4, 2, 'Jim', 4000 ),
        ( 5, 2, 'Kane', 2000 ),
        ( 6, 3, 'Bul', 2500 );

SELECT  c.* ,
        t.TheCount
FROM    #customer c
        INNER JOIN ( SELECT CustomerID ,
                            COUNT(*) AS TheCount
                     FROM   #customer
                     GROUP BY CustomerID
                   ) t ON t.CustomerID = c.CustomerID

DROP TABLE #customer

答案 3 :(得分:0)

试试这个:

B = [1 2 3 4;
     5 6]