我有一个选择查询,其结果表的值如下:
+--------+-----------+-------------+----------------+-------------+----------------+
|SystemId|EquipmentId|ActiveStageId|ActiveStageOrder|StageStatusId|StageStatusOrder|
+--------+-----------+-------------+----------------+-------------+----------------+
| 1 | 288 | 1 | 1 | 3 | 3 |
| 1 | 355 | 1 | 1 | 7 | 6 |
| 1 | 80 | 2 | 3 | 1 | 1 |
| 1 | 288 | 4 | 2 | 1 | 1 |
| 2 | 412 | 4 | 2 | 2 | 2 |
| 2 | 54 | 2 | 3 | 4 | 5 |
+----------------------------------------------------------------------------------+
etc...
我需要将此结果按 SystemId 分组,然后选择: SystemId , EquipmentId , ActiveStageId 的计数对于以前的 ActiveStageId ,最小值为 ActiveStageOrder 和 StageStatusId 的系统分组,如果 StageStatusOrder 为最小值,则为最小值。
我知道如何获取汇总值 min()和 count():
SELECT SystemId, COUNT(EquipmentId) as EqupmentCount,
MIN(ActiveStageOrder) as ActiveStageOrder
FROM [dbo].[Table]
GROUP BY SystemId
但是如何获得最小 ActiveStageOrder 的 ActiveStageId 和最小 StageStatusOrder 的 StageStatusId ?需要获得以上示例的结果:
+--------+-------------+-------------+-------------+
|SystemId|EqupmentCount|ActiveStageId|StageStatusId|
+--------+-------------+-------------+-------------+
| 1 | 4 | 1 | 3 |
| 2 | 2 | 4 | 1 |
+--------------------------------------------------+
答案 0 :(得分:0)
尝试使用窗口功能,如下所示
with cte as (
select SystemId,count(*) over(partition by SystemId) as EqupmentCount,
FIRST_VALUE(ActiveStageId)over(partition by SystemId order by ActiveStageOrder) ActiveStageId,
FIRST_VALUE(StageStatusId) over( partition by SystemId order by ActiveStageOrder,StageStatusOrder) StageStatusId
from table_name
) select distinct * from cte