商家表 (ShopId,Name,Address)商家评论表 (Id,ShopId,UserId,CommentContent,PublishTime)用户表(UserId,UserName)怎样 建立用户的试图 其中一列 是 每个用户 的第一个评论某个商家的 次数(因为 某个shopid 有很多userid 的评论 ,需要知道 第一个(根据PublishTIme)),还有他的评论总数 (这个 简单点 ,搞好了,)附录:
shopid=1 商家 有 
3个评论  userid=1  2007-1-1 (第一个点评者 ),   userid=2 2007-1-2,userid=3 2007-1-4shopid=2 商家有2个评论 userid=3 2007-1-2 (第一个点评者 ),   userid=4 2007-1-8这样统计每个用户 点评总数 就是 userid=1:  1次, userid=2: 1次 ,userid=3 2次,userid=4 : 1次
每个用户是第一个点评的总数 就是 userid=1:1次  userid=3  : 1次

解决方案 »

  1.   

    shopinfo
    shopid shopname
     1     xxxxx
     2     yyyyy
     3     ffffffshopcomment
     commentid  shopid  publishtime  userid
     1            1        2007-1-1  2
     2            1       2007-1-2   3
     3            1      2007-1-3    4 
     4            2       2007-1-1    2
     5            3       2007-1-3    1
     6            2        2007-1-6    1
    试图 是:每个userid 的 第一个评论某个商家的 次数,总的 comment数目userid   firstcomment  allcomment
     1           1              2
     2            2              2
     3             0             1
     4              0             1
      

  2.   

    create table shopinfo(shopid int, shopname varchar(20))
    insert shopinfo select   1,     'xxxxx'
    union all select  2,     'yyyyy'
    union all select  3,     'ffffff'
    go
    create table shopcomment(commentid int, shopid int, publishtime datetime, userid int)
    insert shopcomment select 1,            1,       '2007-1-1',    2
    union all select 2,            1,       '2007-1-2',    3
    union all select 3,            1,       '2007-1-3',    4
     
    union all select 4,            2,       '2007-1-1',    2
    union all select 5,            3,       '2007-1-3',    1
    union all select 6,            2,       '2007-1-6',    1select A.*, 
    firstcomment=isnull(B.firstcomment, 0)
    from
    (
    select userid, 
    allcomment=count(*)
    from shopcomment 
    group by userid
    ) as A
    left join
    (
    select userid, firstcomment=count(*) 
    from shopcomment as tmp
    where not exists(select 1 from shopcomment where shopid=tmp.shopid and publishtime<tmp.publishtime)
    group by userid
    ) as B on A.userid=B.userid--result
    userid      allcomment  firstcomment 
    ----------- ----------- ------------ 
    1           2           1
    2           2           2
    3           1           0
    4           1           0(4 row(s) affected)