Sql Server JOIN,MAX和GROUP BY

时间:2013-07-08 08:25:14

标签: sql-server

我试着拉这个,我有点卡住了。

select 
distinct( msc.id),
 msc.campaignname ,
    max(mst.createdate) as mydate 
from MainMiniSiteCampaign as msc

right join MainMiniSiteTable as mst
on  mst.campaignid = msc.id

order by msc.id
group by msc.id

任何想法我做错了什么?

(错误是“关键字'组'附近的语法不正确)

4 个答案:

答案 0 :(得分:2)

GROUP BY需要在ORDER BY

之前 编辑:我读的那么远:)

由于您仍在进行分组,因此根本不需要distinct

select 
msc.id,
 msc.campaignname ,
    max(mst.createdate) as mydate 
from MainMiniSiteCampaign as msc

right join MainMiniSiteTable as mst
on  mst.campaignid = msc.id

group by msc.id, msc.campaignname

由于group by暗示了MySQL中的一个order,你不需要指定ORDER BY。但您可能希望在组中添加广告系列名称,否则将挑选每个msc.id组的随机广告系列名称。或者在不需要时将其从选择中删除。

答案 1 :(得分:0)

首先你应该按照以下顺序编写组:


group by msc.id
order by msc.id

答案 2 :(得分:0)

试试这个,

select 
distinct( msc.id),
msc.campaignname ,
max(mst.createdate) as mydate 
from MainMiniSiteCampaign as msc

right join MainMiniSiteTable as mst
on  mst.campaignid = msc.id

group by msc.id
order by msc.id

答案 3 :(得分:0)

select 
msc.id,
min( msc.campaignname) ,
max(mst.createdate) as mydate 

from MainMiniSiteCampaign as msc
right join MainMiniSiteTable as mst on  mst.campaignid = msc.id

group by msc.id
order by msc.id

使用distinct(msc.id)

时,您不需要group by msc.id