2014-09-22 27 views
-1

這是我的查詢:爲什麼我的查詢不起作用?

SELECT [MsgType],sr.ServiceName,content,COUNT(*) AS Occurrence 
FROM [VSReceiveSend].[dbo].[ReceiveBuffer] rb 
    INNER JOIN dbo.Services sr ON rb.ServiceCode=sr.Code 
where MsgType is not null and MsgType = 2 
group by MsgType,CONTEnt, sr.ServiceName 
order by COUNT(*) DESC 

UNION 

SELECT [MsgType],sr.ServiceName,content,COUNT(*) AS Occurrence 
FROM [VSReceiveSend].[dbo].ReceivedSMS rb 
    INNER JOIN dbo.Services sr ON rb.ServiceCode=sr.Code 
where MsgType is not null and MsgType = 2 
group by MsgType,CONTEnt, sr.ServiceName 
order by COUNT(*) DESC 

SQL給我這個錯誤:Incorrect syntax near the keyword 'UNION'!問題是什麼?

+0

你想達到什麼目的?看起來像一個相當廣泛的查詢? – 2014-09-22 10:36:23

+6

你在'UNION'關鍵字之前不能有'ORDER BY'子句 – 2014-09-22 10:36:56

+0

@JohnWoo如何在這個查詢中使用UNION? – pejman 2014-09-22 10:48:04

回答

1

一些評論有關查詢:

  • 你可能想union all而不是union。如果兩行碰巧具有完全相同的三個字段,我懷疑你想刪除其中的一個。
  • 您的where條款是多餘的。

(這是除了order by問題。)

SELECT [MsgType], sr.ServiceName, content, COUNT(*) AS Occurrence 
FROM [VSReceiveSend].[dbo].[ReceiveBuffer] rb INNER JOIN 
    dbo.Services sr 
    ON rb.ServiceCode =s r.Code 
where MsgType = 2 
group by content, sr.ServiceName 
UNION ALL 
SELECT [MsgType], sr.ServiceName, content, COUNT(*) AS Occurrence 
FROM [VSReceiveSend].[dbo].ReceivedSMS rb INNER JOIN 
     dbo.Services sr 
     ON rb.ServiceCode = sr.Code 
where MsgType = 2 
group by MsgType, content, sr.ServiceName 
order by Occurrence DESC; 

注意,這會給你多行。如果你想要一個總數,然後在聚合前做union all

SELECT MsgType, sr.ServiceName, content, COUNT(*) AS Occurrence 
FROM (select msgtype, servicecode, content 
     from [VSReceiveSend].[dbo].[ReceiveBuffer] rb 
     where MsgType = 2 
     union all 
     select 
     from [VSReceiveSend].[dbo].ReceivedSMS rb 
     where MsgType = 2 
    ) rb INNER JOIN 
    dbo.Services sr 
    ON rb.ServiceCode = sr.Code 
group by MsgType, content, sr.ServiceName 
order by Occurrence DESC; 
+0

非常感謝您的完整答案,我的朋友。 – pejman 2014-09-23 06:54:53

1

UNION關鍵字前面不能有ORDER BY子句。

如果要通過設置以及COUNT(*)記錄命令,你可以添加一列這樣的:

SELECT [MsgType],sr.ServiceName,content,COUNT(*) AS Occurrence, 1 AS recordset_order 
FROM [VSReceiveSend].[dbo].[ReceiveBuffer] rb 
    INNER JOIN dbo.Services sr ON rb.ServiceCode=sr.Code 
where MsgType is not null and MsgType = 2 
group by MsgType,CONTEnt, sr.ServiceName 
UNION 
SELECT [MsgType],sr.ServiceName,content,COUNT(*) AS Occurrence, 2 AS recordset_order 
FROM [VSReceiveSend].[dbo].ReceivedSMS rb 
    INNER JOIN dbo.Services sr ON rb.ServiceCode=sr.Code 
where MsgType is not null and MsgType = 2 
group by MsgType,CONTEnt, sr.ServiceName 
order by recordset_order ASC, COUNT(*) DESC 
+0

如何在這個查詢中使用UNION? – pejman 2014-09-22 10:48:32

+0

更新了答案 – Bulat 2014-09-22 10:51:26

相關問題