问题
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:
- if I do this as shown in my example here I have a problem with
nvarcharandint. - 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