I have created a temp table, storing the customer details, I want to query the data which group by the CustomerNo and show the ImagePath if IsDefault is set 1.
CREATE TABLE #Temp
(ID varchar(100), CustomerNo varchar(10), IsDefault int, ImagePath varchar(100), ViewCount int)
INSERT INTO #Temp
SELECT '1', 'AC1234', 1, 'xxx1.jpg', 12 UNION ALL
SELECT '2', 'AC1234', 0, 'xxx2.jpg', 42 UNION ALL
SELECT '3', 'AC1234', 0, 'xxx3.jpg', 15 UNION ALL
SELECT '4', 'AC1235', 0, 'xxx4.jpg', 16 UNION ALL
SELECT '5', 'AC1236', 1, 'xxx5.jpg', 13 UNION ALL
SELECT '6', 'AC1234', 0, 'xxx6.jpg', 56 UNION ALL
SELECT '7', 'AC1235', 1, 'xxx7.jpg', 17
SELECT * FROM #Temp
SELECT CustomerNo, MAX(IsDefault) as IsDefault, Sum(ViewCount) as ViewCount FROM #Temp
GROUP BY CustomerNo
DROP TABLE #Temp
Result:
CustomerNo IsDefault ViewCount
---------- ----------- -----------
AC1234 1 125
AC1235 1 33
AC1236 1 13
Can I have a result like this (Show the ImagePath if “IsDefault” = 1)?
CustomerNo IsDefault ViewCount ImagePath
---------- ----------- ----------- -----------
AC1234 1 125 xxx1.jpg
AC1235 1 33 xxx4.jpg
AC1236 1 13 xxx5.jpg
Thank you so much!!
Assuming only one record have the IsDefault flag to 1, this will do the trick:
AFAIK, you need MS-SQL 2008+ to get support for the CTE syntax.