MSSQL-如何为分组选择查询的汇总值获取加法

时间:2019-03-20 08:54:04

标签: sql sql-server

我有一个选择查询,其结果表的值如下:

+--------+-----------+-------------+----------------+-------------+----------------+
|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      |
+--------------------------------------------------+

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