选择多列计算一列,并在一个表中按一列分组

时间:2018-06-02 00:25:00

标签: sql sql-server group-by count

我有一个名为[delivery]的表,列[ID],[Employee],[Post],[c_name],[Deli_Date],[note]

我需要选择所有列并计算Employee,然后按Employee分组。 表中的数据如下:

  ---------------------------------------------------
  | Employee| Post      |c_name  |Deli_Date   |Note |
  |---------|-----------|---------------------|-----|
  |  DAVID  |MANAGER    | a      |11/11/2018  |note |
  |  DAVID  |MANAGER    | b      |01/01/2015  |note |
  |  SAM    |ACOUNTS    | c      |10/10/2016  |note |
  |  DAVID  |IT         | a      |10/02/2015  |note |
  |  DAVID  |DOCTOR     | c      |20/02/2017  |note |
  |  JAMES  |DELIVERYMAN| b      |05/05/2015  |note |
  |  OLIVER |DRIVER     | b      |02/02/2014  |note |
  |  SAM    |ACOUNTS    | c      |02/02/2012  |note |

此代码:

select Employee, count(Employee) as TIMES from delivery
group by Employee

结果是:(但我也需要显示其他列。)

| Employee| TIMES | 
|---------|-------|
|  DAVID  |   4   |
|  JAMES  |   1   |
|  OLIVER |   1   |
|  SAM    |   2   |

我需要我的代码显示像这样:

| Employee| TIMES | Post      |c_name  |Deli_Date   |Note |
|---------|-------|-----------|---------------------|-----|
|  DAVID  |   4   |MANAGER    | a      |11/11/2018  |note |
|  JAMES  |   1   |DELIVERYMAN| b      |05/05/2015  |note |
|  OLIVER |   1   |DRIVER     | b      |02/02/2014  |note |
|  SAM    |   2   |ACOUNTS    | c      |10/10/2016  |note |

什么是最好的查询可以给我这个结果?

查看列[c_name],[Deli_Date],它们显示最后插入的数据。 或者只是在没有[c_name],[Deli_Date]的情况下给我结果。

3 个答案:

答案 0 :(得分:1)

如果您想要最后一个日期和计数,您可以使用窗口函数:

select d.Employee, d.cnt, d.Post, d.c_name, d.Deli_Date, d.Note 
from (select d.*,
             count(*) over (partition by employee) as cnt,
             row_number() over (partition by employee order by deli_date desc) as seqnum
      from delivery d
     ) d
where seqnum = 1;

答案 1 :(得分:1)

nose

答案 2 :(得分:0)

您需要在select和group by子句中包含所有非聚合列

<Array<Brand>>

Max(Deli_date)会给你最新的日期。

要获取最新的c_name,note,post等,您需要一个带有按deli_date排序的rank函数的子查询。我稍后会添加这个例子。