出现次数的不同值

时间:2016-09-07 18:58:15

标签: sql-server count

我想计算一个供应商标题在结果集中出现的次数,但是如果我使用COUNT结合GROUP BY,我只在结果集中得到0或1

e.g。我的结果现在看起来像这样:

id   vendortitle      cnt
184  Hotel            1
198  A3               1
199  Las Vegas        1
200  Hotel-Restaurant 1
1252 Hansen           1
1253 Sunrise          1
1255 NULL             0
1256 Winsel           1
1257 Olde North       1
1258 A Castle         1
1259 A Castle         1
1262 Restaurant Rich  1
1263 NULL             0
1264 NULL             0
1265 NULL             0
1266 NULL             0
1269 My venue         1
1270 My venue         1
1271 My venue         1
1272 My venue         1

但是我想要这个(我实际上并不需要NULL值):

id   vendortitle      cnt
184  Hotel            1
198  A3               1
199  Las Vegas        1
200  Hotel-Restaurant 1
1252 Hansen           1
1253 Sunrise          1
1255 NULL             5
1256 Winsel           1
1257 Olde North       1
1258 A Castle         2
1262 Restaurant Rich  1
1269 My venue         4

我的SQL声明:

SELECT DISTINCT(vendortitle),id,COUNT(vendortitle) as cnt FROM (select ROW_NUMBER() OVER (ORDER BY vendortitle DESC) as RowNum,
id,vendortitle
FROM 
(
    SELECT 
      uf.id,coalesce(l.title, a.title) as vendortitle
    FROM userfavorites uf
    INNER JOIN vendor_photos vp ON uf.objectid = vp.id 

            LEFT JOIN homes l on vp.objecttype= 1 and vp.objectid = l.id
            LEFT JOIN hotels a on vp.objecttype= 2 and vp.objectid = a.id

    ) as info

) as allinfo
WHERE RowNum >          0 AND RowNum <=         50
GROUP BY vendortitle,RowNum, id

1 个答案:

答案 0 :(得分:1)

您的查询中有很多内容是您不需要的。派生表并非真正需要,DISTINCTROW_NUMBER也是如此。这应该做的工作:

SELECT  MIN(uf.id) id,
        COALESCE(l.title, a.title) as vendortitle,
        COUNT(*) as cnt
FROM userfavorites uf
INNER JOIN vendor_photos vp 
    ON uf.objectid = vp.id 
LEFT JOIN homes l 
    ON vp.objecttype= 1 
    AND vp.objectid = l.id
LEFT JOIN hotels a 
    ON vp.objecttype = 2 
    AND vp.objectid = a.id
GROUP BY COALESCE(l.title, a.title);