min的子查询(字段值)

时间:2016-05-03 18:30:13

标签: sql-server subquery

  

我有一个查询,它会查找状态为'6'(未完成)的任何'Open_Tollgates'以及负责'部门'。

我只想检索min(pgAct.Gate_ID)(第一个未完成的Gate_Number)。

问题是,每个收费站(即'706')是不同的,因为它具有特定的活动ID(未显示)。

我知道我需要做一个子查询来过滤数据。如下所示,我基本上需要只是第一行(706 3 Sourcing)。

你会推荐什么?

在子查询之前:

select pgAct.ID as Open_Tollgate, pgAct.Gate_ID as Gate_Number, secGroup.[Group] as Department
from [dbo].[Project_Gate_Activities] pgAct
join [dbo].[Activities] as Act
on pgAct.activity_order = Act.order_id
join [dbo].[Security_Group] as secGroup
on Act.group_id = secGroup.group_id
where pgAct.ID = 706 
and status_id = 6
group by pgAct.id, pgAct.gate_id, secGroup.[Group]
  

在子查询结果集之前:

706 3采购

706 4会计

706 4财务

706 4后勤

706 5 IT

706 6会计

706 6财务

706 6采购

706 7 IT

706 7销售

706 8会计

1 个答案:

答案 0 :(得分:0)

您可以尝试使用ROW_NUMBER ..您需要使用子查询或类似的cte。

;WITH cte AS 
    (SELECT  pgAct.ID AS Open_Tollgate,
            pgAct.Gate_ID AS Gate_Number,
            secGroup.[Group] AS Department,
            ROW_NUMBER() OVER (PARTITION BY pgAct.ID ORDER BY pgAct.Gate_ID) Rn
    FROM    [dbo].[Project_Gate_Activities] pgAct
            JOIN [dbo].[Activities] AS Act ON pgAct.activity_order = Act.order_id
            JOIN [dbo].[Security_Group] AS secGroup ON Act.group_id = secGroup.group_id
    WHERE   pgAct.ID = 706
            AND status_id = 6
    GROUP BY pgAct.id,
            pgAct.gate_id,
            secGroup.[Group]
    )
SELECT * FROM cte WHERE Rn = 1

如果你一次只选择一个pgAct.ID ..你也可以使用SELECT TOP 1,就像这样

SELECT TOP 1 
        pgAct.ID AS Open_Tollgate,
        pgAct.Gate_ID AS Gate_Number,
        secGroup.[Group] AS Department,
FROM    [dbo].[Project_Gate_Activities] pgAct
        JOIN [dbo].[Activities] AS Act ON pgAct.activity_order = Act.order_id
        JOIN [dbo].[Security_Group] AS secGroup ON Act.group_id = secGroup.group_id
WHERE   pgAct.ID = 706
        AND status_id = 6
ORDER BY pgAct.ID, 
        pgAct.Gate_ID