两张桌子。一个包含项目列表,另一个包含项目的各个阶段。 我需要展示项目的最新阶段。 我现在的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
谢谢大家!
答案 0 :(得分:4)
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
答案 1 :(得分:0)
;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