【问题标题】:Limit results in join限制加入的结果
【发布时间】:2014-05-03 01:25:51
【问题描述】:

两张桌子。一个包含项目列表,另一个包含项目的阶段。 我需要展示项目的最新阶段。 我目前拥有的 SQL 显示了所有阶段,看起来像这样:

SELECT
    a.proj_name,
    a.proj_phase,
    c.proj_actions_next_action,
    c.proj_actions_next_action_date
FROM
    projects a  
LEFT OUTER JOIN
    Projects_actions c
        ON a.proj_id = c.proj_actions_projects_link
LEFT OUTER JOIN
    Clients b
        ON a.proj_clientlink = b.client_id
ORDER BY b.clientname

输出看起来像这样:

proj_name | proj_phase | proj_actions_next_action | proj_actions_next_action_date
Denmark   | Active     | Call X person            | 1/1/2014
Denmark   | Active     | Call Y person            | 2/1/2014
Denmark   | Active     | Do this presentation     | 3/1/2014
Denmark   | Active     | Sell this product        | 4/1/2014
UK Asset  | Active     | Call Y person            | 1/2/2014
UK Asset  | Active     | Call X person            | 1/3/2014
UK Asset  | Active     | Call Y person            | 2/4/2014
UK Asset  | Active     | Do this presentation     | 3/5/2014
UK Asset  | Active     | Sell this product        | 4/6/2014

我希望它看起来像这样:(仅显示最新的 proj_actions_next_action_date)

proj_name | proj_phase | proj_actions_next_action | proj_actions_next_action_date
Denmark   | Active     | Sell this product        | 4/1/2014
UK Asset  | Active     | Sell this product        | 4/6/2014

谢谢大家!

【问题讨论】:

  • 只要得到最大(日期)。

标签: sql sql-server tsql join outer-join


【解决方案1】:
SELECT  Q.proj_name,
        Q.proj_phase,
        Q.proj_actions_next_action,
        Q.proj_actions_next_action_date
FROM (
SELECT
    a.proj_name,
    a.proj_phase,
    c.proj_actions_next_action,
    c.proj_actions_next_action_date,
    ROW_NUMBER() OVER (PARTITION BY a.proj_name 
           ORDER BY c.proj_actions_next_action_date DESC) AS RN
    ,b.clientname

FROM
    projects a  
LEFT OUTER JOIN
    Projects_actions c
        ON a.proj_id = c.proj_actions_projects_link
LEFT OUTER JOIN
    Clients b
        ON a.proj_clientlink = b.client_id
    )Q
WHERE Q.RN = 1
ORDER BY Q.clientname

【讨论】:

  • 我也是!顺便说一句,它似乎没有使用Clients table。
  • 它使用 clients 表对每个客户的结果进行排序。
  • 我现在正在研究这些并将它们实施到我当前的项目中。我会让你知道我过得怎么样 :)
  • +1 是唯一一个获得“order by”权利的人。也许您应该在 row_number 部分中为列添加前缀?
  • 是的,这段代码很有效。非常感谢所有的帮助!还有 t-clausen.dk,我不知道这意味着什么,我对 SQL 很陌生,但无论如何它都可以工作。哈哈谢谢大家!
【解决方案2】:
;with cte1 as
(
SELECT
    a.proj_name,
    a.proj_phase,
    c.proj_actions_next_action,
    c.proj_actions_next_action_date
FROM
    projects a  
LEFT OUTER JOIN
    Projects_actions c
        ON a.proj_id = c.proj_actions_projects_link
LEFT OUTER JOIN
    Clients b
        ON a.proj_clientlink = b.client_id
ORDER BY b.clientname
),
cte2 as

(
  ROW_NUMBER() OVER(PARTITION BY proj_name ORDER BY proj_actions_next_action_date DESC) AS Row,
  *
  from cte1

)

select * from cte2
where Row =1

【讨论】:

    猜你喜欢
    • 2014-09-22
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 2020-01-06
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多