SQL中的join语句后的case语句

时间:2015-02-11 15:12:51

标签: sql join case

下面的数据,我需要为col2 = 1选择col4 = 301。我使用像

这样的查询加入了几个表后得到了数据
/****** Script for SelectTopNRows command from SSMS  ******/
Select count(*),t.intWeightTypeId,t.locationid,t.airoccupancycode
from
(SELECT * 
FROM [AIRWork].[dbo].[t1551_c1_LOSS_StagingLocation_0A578891-5DF8-4F77-8AC4-0A9480148F1F] a
join [AIRGeography].[dbo].[TblSourceTargetMap_US] b on a.guidareaexternal=b.guidExternalSource
where locationtypecode='R' ) t 
group by t.intWeightTypeId,t.locationid,t.airoccupancycode
order by t.locationid


col1   col2       col3           col4
9   4   Loc_PE_14208    301
31  1   Loc_PE_14208    301
9   3   Loc_PE_14208    301
9   2   Loc_PE_14208    301
14  2   Loc_PE_14209    301
32  1   Loc_PE_14209    301
14  4   Loc_PE_14209    301
14  3   Loc_PE_14209    301
14  2   Loc_PE_14210    301

1 个答案:

答案 0 :(得分:2)

您应该使用where子句执行此操作。假设列与SELECT中的列匹配,则应使用列名称。您也不需要子查询来执行group by

  SELECT count(*), intWeightTypeId, locationid, airoccupancycode 
  FROM [AIRWork].[dbo].[t1551_c1_LOSS_StagingLocation_0A578891-5DF8-4F77-8AC4-0A9480148F1F] a join
       [AIRGeography].[dbo].[TblSourceTargetMap_US] b
        on a.guidareaexternal=b.guidExternalSource
  WHERE locationtypecode = 'R' AND
        airoccupancycode = 301 and intWeightTypeId = 1
  GROUP BY intWeightTypeId, locationid, airoccupancycode 
  ORDER BY locationid