如何在左外连接操作后选择不同的值

时间:2015-10-07 00:33:44

标签: sql-server

我想从三个具有聚合函数的表中选择一些值,但在其中一列中没有重复,例如:

select t3.ValueDesc as FeatureType,  
        count(t2.Strategic) as TotalCount
        ,t2.RequestID,t1.StoryID    --these are not needed, but put for better vision

from  tblRequests t2  
left outer join (select * from tblAgileMultiDD where Type=18) t3
    on t3.FormulaValue = t2.Strategic 
left outer join tblAgileStory t1 
    on t1.Feature = t2.RequestID  

where t2.RequestID > 0  
and t1.DemoStatus = 1  

group by t3.ValueDesc
     ,t2.RequestID, t1.StoryID    --these are not needed but put for better vision
order by t3.ValueDesc

然后它会给我这样的东西:

FeatureType     TotalCount  RequestID   StoryID
Protect Base    1           311         1629
Protect Base    1           311         1630
Protect Base    1           312         1631
Protect Base    1           312         1637
New Market      1           313         1640
New Market      1           313         1645

如果我用“,t2.RequestID,t1.StoryID”注释掉行,它会给我结果:

FeatureType     TotalCount
Protect Base    4         
New Market      2

因此,对于RequestID和StoryID的每个唯一组合,它返回新行。如何使它只为每个唯一的RequestID返回新行,而不管StoryID? 所以我希望这个查询结果如下:

FeatureType     TotalCount
Protect Base    2          (for RequestID = 311, 312)
New Market      1          (for RequestID = 313)

在开头添加“distinct”字样不会对其产生影响。 你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

select distinct FeatureType,TotalCount from (
    select t3.ValueDesc as FeatureType,  
            count(t2.Strategic) as TotalCount
            ,t2.RequestID
            -- ,t1.StoryID    --these are not needed, but put for better vision

    from  tblRequests t2  
    left outer join (select * from tblAgileMultiDD where Type=18) t3
        on t3.FormulaValue = t2.Strategic 
    left outer join tblAgileStory t1 
        on t1.Feature = t2.RequestID  

    where t2.RequestID > 0  
    and t1.DemoStatus = 1  

    group by t3.ValueDesc
         ,t2.RequestID
          -- , t1.StoryID    --these are not needed but put for better vision
) as T

按t3.ValueDesc排序

你可以尝试一下。