2015-02-11 206 views
0

下面的数据,我需要选择col4 = 301仅适用于col2 = 1。我得到的数据使用查询像加入几桌后 -SQL语句中加入语句后的case语句

/****** 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

'where col4 = 301 and col2 = 1'?不知道你在... – 2015-02-11 15:18:01

+1

什么是问题?你为什么不添加一个'WHERE'语句? – 2015-02-11 15:18:04

回答

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