0

目标是获取每个活动花费太多时间的顶级活动:

在 mysql 中应该很容易:

select description, reference, person, max(minutes)
group by description

结果应该带回来:

描述 参考 分钟
活动一 AA32343 安倍 10
活动 B BB34345 鲍里斯 8
活动 C CCsdeee 约翰 12

但在 Microsoft SQL 中,它不会运行,因为 group by 没有选择中的所有列...

什么相当于 MS SQL 中的 mysql 查询?如果我在 group by 中添加我需要的所有列,我将获得所有行,这不是我想要的

这是一个非常常见的问题,有人可以找到答案并发布查询并以可以将答案应用于几乎所有类似问题的方式进行解释吗?提前致谢

表中的行具有如下信息:

描述 参考 分钟
活动一 AA32343 安倍 10
活动一 AA77340 威尔逊 9
活动一 AA56341 卡尔 4
活动 B BB34345 鲍里斯 8
活动 B BB94342 6
活动 B BB64343 玛莎 3
活动 C CCsdeee 约翰 12
活动 C CCs5ee4 彼得 10
活动 C CCskee5 扫罗 4
4

4 回答 4

3

使用 row_number()

select * from (select description, reference, person, minutes,
row_number() over(partition by description order by minutes desc) rn from table_name
) a where rn=1
于 2022-02-18T18:30:41.640 回答
1

实际上,您在 MySQL 中执行的查询是无效的 group by 查询。例如,您如何决定“活动 A”是参考“AA32343”?可能只是忽略它来自哪一行。然后你也可以简单地在这些列上使用聚合:

select description, min(reference) reference, min(person) person, max(minutes)
from myTable
group by description;

或者,如果您的意思是这些字段来自具有 max(minutes) 的行,那么:

select t.*
from myTable t
inner join (
select description, max(minutes) maxMin
from myTable
group by description) tmp on t.description = tmp.description and t.Minutes = tmp.maxMin;
于 2022-02-18T18:39:03.003 回答
0

使用analytic window function

with cte as

(select *, max(minutes) over (partition by description) as max_minutes
 from your_table)


select description, reference, person, minutes
from cte
where minutes=max_minutes;
于 2022-02-18T18:52:08.953 回答
0

这里的问题是您省略了元素,因为您似乎并不关心要为每个分组显示哪个 Reference 和 Person。

获得所需结果的一种方法是使用 CTE 获得每个描述的 Max minutes,然后附加其他列。对于这个例子,我得到了按描述排序的第一个参考和人员:

;with cte as
(
select  Description, 
        Minutes = max(Minutes)
from myTable MT
group by Description
)
Select  C.Description,
        R.Reference,
        R.Person,   
        C.Minutes
From cte C
Cross Apply
(
    Select top 1    T.Reference,
                    T.Person
    From myTable T
    where T.Description = C.Description
    order by T.Description
) R
于 2022-02-18T20:36:56.277 回答