如何在sql中的select查询中仅对某些项使用distinct

时间:2016-09-15 14:38:24

标签: sql sql-server

我有这样的查询

select F.F_Stand,    
       T_Exhibitor.F_Exhibitor_Name,
       f.F_Localcontact,
       F.F_status
from T_Exhibitor_followup F
left join T_Exhibiton
    on T_Exhibitor.F_Exhibitor_Code = F.F_Exhibitor_Code 
where F_Exhibition_Code='12511' and
      F_Area='DWTC' and
      F_Building='SAEED' and
      F_catcode='FN'

我这样说:

 Stand no     Name                  number  status
Saeed E136  A. Proctor Group Ltd    123     Pending
Saeed E136  A. Proctor Group Ltd    123     Pending
Saeed E136  A. Proctor Group Ltd    123     Pending
Saeed E136  A. Proctor Group Ltd    123     Delivered

我想只获得1行,如果状态全部已发送,那么我想要显示状态'已发送'如果任何一个状态'等待'然后我想显示状态'待定' 所以我添加了这样的查询:在这个查询中我添加了不同的关键字

select  distinct  F.F_Stand, T_Exhibitor.F_Exhibitor_Name,f.F_Localcontact,F.F_status
from T_Exhibitor_followup F left join T_Exhibitor on T_Exhibitor.F_Exhibitor_Code=F.F_Exhibitor_Code 
where F_Exhibition_Code='12511' and F_Area='DWTC' and F_Building='SAEED' and F_catcode='FN'    

但现在我这样出来了:

Saeed E136  A. Proctor Group Ltd    123 Delivered
Saeed E136  A. Proctor Group Ltd    123 Pending

仍未获得

2 个答案:

答案 0 :(得分:3)

这是一个聚合查询。你可以这样做:

 public JsonResult UpdateEvent(.........)
 {
   List<Guid> usersChanged = new List<Guid>();
   .
   .
   .
   if(usersChanged.Count() > 0)
   {
    //Here is where i want to call a confirmation box
   }
   .
   .
   .
   return Json(eventId, JsonRequestBehavior.AllowGet);
}

SELECT F.F_Stand, e.F_Exhibitor_Name, f.F_Localcontact, CASE WHEN MIN(F.F_status) = MAX(f.F_status) THEN MIN(F.F_status) WHEN SUM(CASE WHEN F.F_status = 'Pending' THEN 1 ELSE 0 END) > 0 THEN 'Pending' ELSE '???' END FROM T_Exhibitor_followup F LEFT JOIN T_Exhibitor e ON e.F_Exhibitor_Code = F.F_Exhibitor_Code WHERE F_Exhibition_Code = '12511' AND F_Area = 'DWTC' AND F_Building = 'SAEED' AND F_catcode = 'FN' GROUP BY F.F_Stand, e.F_Exhibitor_Name, f.F_Localcontact; 的逻辑是:

  • 如果所有状态都相同,则使用该状态。
  • 如果有任何待处理状态,请将其称为case
  • 否则,输出'Pending'

答案 1 :(得分:2)

您可以使用ROW_NUMBER来优先'Pending'超过'Delivered'状态:

select F.F_Stand,    
       T_Exhibitor.F_Exhibitor_Name,
       f.F_Localcontact,
       F.F_status
from (
   select F.F_Stand,    
          T_Exhibitor.F_Exhibitor_Name,
          f.F_Localcontact,
          F.F_status,
          ROW_NUMBER() OVER (ORDER BY CASE 
                                         WHEN F.F_status = 'Pending' THEN 0 
                                         ELSE 1
                                      END) AS rn
   from T_Exhibitor_followup F
   left join T_Exhibiton
       on T_Exhibitor.F_Exhibitor_Code = F.F_Exhibitor_Code 
  where F_Exhibition_Code='12511' and
         F_Area='DWTC' and
         F_Building='SAEED' and
         F_catcode='FN') as t
where t.rn =1 

上述查询有效,前提是two字段只有status个可能的值:

  • 'Pending'
  • 'Delivered'

您可以在窗口函数的ORDER子句中添加一个额外字段,以便为具有相同status值的记录划分优先级。