Concatenate nvarchar and int while maintaining Distinct result

邮差的信 提交于 2019-12-24 07:17:00

问题


I'm trying to count all the items for each brand and concatenate the brand name + number of items.

I have this query in SQL Server 2008 R2:

SELECT DISTINCT 
    Brands.BrandName + ' ' + COUNT(Items.ITEMNO) as ITEMSNO,
    Brands.BrandId
FROM Items, Brand_Products, Brands
WHERE    
    Items.ITEMNO=Brand_Products.ItemNo
    AND Brands.BrandId=Brand_Products.BrandId
    AND Items.SubcategoryID='SCat-020'
GROUP BY 
    Brands.BrandId,
    Brands.BrandName,
    Items.ITEMNO

I'm trying to concatenate 2 fields, but I have 2 problems:

  1. if I do this as shown in my example here I have a problem with nvarchar and int.
  2. if I use convert I have a problem with (Distinct)

Any help? :)


回答1:


This will work, fist you count items based on BrandId in CTE and than join it with Brand table.

WITH    ItemCount
      AS ( SELECT BrandId
               ,COUNT(Items.ITEMNO) AS item_Count
            FROM Items
               ,Brand_Products
               ,Brands
            WHERE Items.ITEMNO = Brand_Products.ItemNo
                AND Brands.BrandId = Brand_Products.BrandId
                AND Items.SubcategoryID = 'SCat-020'
            GROUP BY Brands.BrandId)
SELECT b.BrandName + ' ' + CONVERT(VARCHAR(5), Item_Count)
    FROM Brands AS b
    JOIN ItemCount AS I
        ON b.BrandId = i.BrandId



回答2:


Retrieve the field you're looking for twice, once in the concatenated field answer, and once by itself. This should solve your issue with DISTINCT.




回答3:


Convert to varchar before concatenating

'Whatever ' + CONVERT(VARCHAR(8), COUNT(Items.ITEMNO)) + ' Whatever '


来源:https://stackoverflow.com/questions/21143335/concatenate-nvarchar-and-int-while-maintaining-distinct-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!