2016-09-24 47 views
0

OK刪除重複值,所以我有一個名爲NewsEvent這些列的表:新聞臺基於一個塔

  • NewSID的
  • 事件ID
  • 用戶名
  • SameEvent

現在我只處理前3列,基本上我想要做的是獲得與同一事件相關的號碼新聞,但是t他的問題是多個用戶可以將某個新聞鏈接到一個事件,而我只需要將該新聞計算一次。

假設有ID = 1的事件,有5個新聞和3個用戶已將這5個新聞與事件關聯起來,使用我的查詢我會得到與該事件相關的15條新聞的結果。

現在本身的查詢是正確的,但我怎麼能修改計數基礎上,新聞欄目的時候來算新聞只有一次,並刪除重複的值,所以它返回的結果是5,而不是15

我的查詢如下:

Select count(NE.NewsID) as [Number of news linked to the event], NE.EventID as EventID 
From NewsEvent NE 
Group By NE.EventID 
Order By Count(NE.NewsID) Desc 

我使用SQL Server 2014

回答

2

我覺得你只是想count(distinct)

Select count(distinct NE.NewsID) as [Number of news linked to the event], 
     NE.EventID as EventID 
From NewsEvent NE 
Group By NE.EventID 
Order By Count(NE.NewsID) Desc; 
+0

omg,我把括號放在了括號之前,並想知道爲什麼它不工作,不在裏面,我不敢相信我很愚蠢。 – Legjendat

1


嗨,
您可以使用下面的查詢,

隨着出重複(重複值)

Select count(distinct NE.NewsID) as [Number of news linked to the event], NE.EventID as EventID 
From NewsEvent NE 
Group By NE.EventID 
Order By Count(NE.NewsID) Desc 

只有複製

Select count(NE.NewsID) as [Number of news linked to the event], NE.EventID as EventID 
From NewsEvent NE 
Group By NE.EventID 
Order By Count(NE.NewsID) Desc having count(NE.NewsID) > 1