如何从事实表中获取子查询中的不同id

时间:2017-10-30 16:01:53

标签: sql sql-server tsql

尝试返回子查询中的所有字段减去事实表cor.score中的重复子ID。我不希望重复的ID会夸大我的计数。每个id都需要计算一次。

select distinct cs.childid
from
(select s.sitename, c.primarylanguage, count(Primarylanguage) as 'Count'
from cor.scores cs
left join cor.sites s on s.id = cs.siteid
left join cor.children c on c.id = cs.childid
group by s.sitename, c.primarylanguage)

错误:

Msg 102, Level 15, State 1, Line 7 Incorrect syntax near ')'.

最好的方法是什么?

2 个答案:

答案 0 :(得分:0)

select distinct cs_childid
from
(

select s.sitename,cs.childid as cs_childid, c.primarylanguage, count(Primarylanguage) as 'Count'
from cor.scores cs
left join cor.sites s on s.id = cs.siteid
left join cor.children c on c.id = cs.childid
group by s.sitename, c.primarylanguage,cs.childid

)as T  

答案 1 :(得分:0)

你想要这个:    1.可以返回任何子查询列

    select  s.childid,s.[Count]
    FROM (
        SELECT s.sitename, c.primarylanguage,cs.childid, count(Primarylanguage)OVER(PARTITION BY s.sitename) as 'Count'
        FROM cor.scores cs
        LEFT join cor.sites s on s.id = cs.siteid
    ) AS s LEFT join cor.children c on c.id = s.childid

或者这个:    2.只能返回组列和聚合列

    select  s.childid,s.[Count]
    FROM (
        SELECT s.sitename,cs.childid, count(Primarylanguage)OVER(PARTITION BY s.sitename) as 'Count'
        FROM cor.scores cs
        LEFT join cor.sites s on s.id = cs.siteid
        GROUP BY s.sitename,cs.childid
    ) AS s LEFT join cor.children c on c.id = s.childid