需要SQL Server查询帮助

时间:2016-03-17 16:08:49

标签: sql sql-server select union union-all

我在视图中存储了一堆数据(将MS Access查询转换为视图)。现在我要做的是编写一个存储过程来根据添加数据的时间来提取数据。这是我正在运行的查询

(Select *,  row_number() over (partition by PlanID Order BY AddedonDate *ASC*)

所以这会把我的所有数据都拉好。我必须解决的问题是,客户端实际上是第一个appt和第二个appt - 基本上我需要为最新日期以及EARLIEST提取数据,并在我的查询中包含'2ndAppt'。所以1stAppt和2ndAppt持有一个字符串值,我稍后会使用...... 2个值可能会有所不同,从1stAppt到2ndAppt - 只有AddedOn日期会告诉我是否有不同的(最早为1stAppt,最新为2ndAppt)。 / p>

Select 
    Name, PlanID, ApptDate, 1stAppt, 2ndappt, rn, 
From 
    (Select 
         *,   
         row_number() over (partition by PlanID Order BY AddedonDate desc) as rn 
     From  vClientInfo

     Union All

     Select 
         Name, PlanID, ApptDate, 1stAppt, 2ndAppt, rn, 
     From 
         (Select 
              *,  
              row_number() over (partition by PlanID Order BY AddedonDate asc) as rn 
          From vClientInfo

所以我这样做了,我改变了这个......

//Retriving 'text'
$idText = ["text"];
echo "$idText";

但是我不确定这是否正在提取正确的数据,因为我正在使用大量数据并且难以验证。所以基本上我需要做一个联合,这样我的两个查询都会输入正确的数据。最初我得到了1920条记录,所以有了一个联盟,我应该得到的数量也是如此,但是,这个数字是两倍所以3840,为什么?

  $response = curl_exec($curl);
  $response = json_decode($response);
  $idText = $response->text;

1 个答案:

答案 0 :(得分:2)

你正在使用窗口功能,但你没有过滤它,所以重点是什么?如果您想要最早和最新,请选择rn = 1:

Select Name, PlanID, ApptDate, 1stAppt,2ndappt, rn,
from (Select *,
            row_number() over (partition by PlanID Order BY AddedonDate desc) as rn
     from  vClientInfo
     Union All
     Select *, 
           row_number() over (partition by PlanID Order BY AddedonDate asc) as rn 
     from  vClientInfo)
WHERE rn = 1

如果您想要最早的第一个应用程序和最新的第二个应用程序:

Select Name, PlanID, ApptDate,
       MAX(CASE WHEN rnk = 1 then 1stAppt end) as 1stAppt,
       MAX(CASE WHEN rn = 1 THEN 2ndappt end) as 2ndAppt
from (Select *,
            row_number() over (partition by PlanID Order BY AddedonDate desc) as rn,
     0 as rnk
     from  vClientInfo
     Union All
     Select *,
           0 as rn,
           row_number() over (partition by PlanID Order BY AddedonDate asc) as rnk 
     from  vClientInfo)
GROUP BY Name,PlanID,ApptDate