1
我創建了一個臨時表,存儲客戶的詳細信息,我想查詢該組由CustomerNo數據並顯示的ImagePath如果ISDEFAULT設置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
結果:
CustomerNo IsDefault ViewCount
---------- ----------- -----------
AC1234 1 125
AC1235 1 33
AC1236 1 13
我可以有這樣的結果(如果「IsDefault」= 1,顯示ImagePath?)?
CustomerNo IsDefault ViewCount ImagePath
---------- ----------- ----------- -----------
AC1234 1 125 xxx1.jpg
AC1235 1 33 xxx4.jpg
AC1236 1 13 xxx5.jpg
非常感謝!
如果有幾行'Max(IsDefault)'會怎麼樣? – zerkms
假設相同的CustomerNo將只有1條記錄IsDefault = 1 –
然後刪除'GROUP BY'並選擇'WHERE IsDefault = 1' – zerkms