这是我的疑问:
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 :(得分: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
答案 1 :(得分: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;