在sql中获取查询之外的变量

时间:2013-10-15 09:35:10

标签: sql

我知道我的头衔有点误导,但我不确定什么是好头衔。

Authored有2列,即ID,PubID

无论如何我可以将P输出到我的结果中。

我想知道每个相应的ID,PubID对,有多少行具有相同的PubID但ID不同。

select a.authorId, P 
from Authored A 
WHERE 1 < 

(Select count(*) as P
from Authored B
where A.pubId = B.pubId
AND A.authorId<> B.authorId)

感谢所有回答的人。


AuthorID       pubID
1                2
3                2
4                2
10               1
11               1 

预期结果

AuthorID     NumberOfOccurenceOfDiffAuthIDWithSamePubID
1                       3
3                       3
4                       3
10                      2
11                      2

3 个答案:

答案 0 :(得分:1)

使用count() over()更新:

<强> Fiddle demo

select a.AuthorId, count(*) over(partition by pubId) counts
from Authored a 
order by a.AuthorId;

答案 1 :(得分:0)

请尝试以下MS Sql server查询:

select 
    *, 
    COUNT(*) over (partition by pubId) 
From Authored  
where authorId<>pubId

答案 2 :(得分:0)

这是你的意思,不清楚你在问什么? Fiddle here

select
    count(ID) P,
    PubID
from
    (select distinct ID, pubID from Authored) d
group by
    PubID

This will give you the number of distinct `ID/authorId` for each `PubID\pubId`