按客户名称分组

时间:2013-11-12 05:39:41

标签: sql-server

Demo

SELECT ROW_NUMBER() OVER (ORDER BY Visit_Date DESC,P_Master.P_Name ASC) AS RowNumber, 
P_Master.P_Name,
(SELECT MAX(Visit_Date) FROM P_Visit v WHERE v.PID = p_Master.PID) as Visit_Date
FROM P_Master
LEFT JOIN P_VISIT
ON P_Master.PID=P_VISIT.PID
WHERE P_Master.P_Name LIKE 'j%'

如果我在“2013-10-29”上搜索,我必须显示“访问日期”列的最大日期,然后记录显示那些客户的日期为“2013-10-29”,我必须显示客户的最长日期 所有工作正常,但如何通过PID制作组(我必须只显示给定搜索的一条记录)

2 个答案:

答案 0 :(得分:1)

请尝试以下查询,它也有助于分页

SELECT ROW_NUMBER() OVER (ORDER BY Visit_Date DESC,P_Name ASC) AS RowNumber, * 
FROM (SELECT DISTINCT P_Master.P_Name,
(SELECT MAX(Visit_Date) FROM P_Visit v WHERE v.PID = p_Master.PID) as Visit_Date
FROM P_Master
LEFT JOIN P_VISIT
ON P_Master.PID=P_VISIT.PID
WHERE P_Master.P_Name LIKE 'j%') tbl

答案 1 :(得分:0)

这将有效:

  SELECT DISTINCT
  P_Master.P_Name,
  (SELECT MAX(Visit_Date) FROM P_Visit v WHERE v.PID = p_Master.PID) as Visit_Date
  FROM P_Master
  LEFT JOIN P_VISIT
  ON P_Master.PID=P_VISIT.PID
  WHERE P_Master.P_Name LIKE 'j%'