我有一个名为[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 |什么是最好的查询可以给我的结果?
参见columns [c_name],[Deli_Date],它们显示最后插入的数据。或者直接给我没有[c_name],[Deli_Date]的结果,没问题。
发布于 2018-06-02 09:16:19
如果您想要最后的日期和计数,您可以使用窗口函数:
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;发布于 2018-06-02 08:54:43
您需要在select和group by子句中包括所有非聚合列
select Employee,
count(Employee) as TIMES,
max(Deli_date) as LAST_DELI_DATE,
post,
note
from delivery
group by Employee, post, noteMax(Deli_date)会给你最新的日期。
要获得最新的c_name、note、post等信息,您需要一个带有按deli_date排序的rank函数的子查询。我将在稍后添加该示例。
发布于 2018-06-02 14:58:59
select Employee, count(Employee) as TIMES,Post,c_name,Deli_Date,Note from delivery
group by Employeehttps://stackoverflow.com/questions/50652440
复制相似问题