如何在最大记录上获得其他字段?

时间:2012-11-21 04:05:13

标签: sql sql-server tsql

我创建了一个临时表,存储客户详细信息,我想查询CustomerNo分组的数据,如果IsDefault设置为1,则显示ImagePath。

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

非常感谢!!

1 个答案:

答案 0 :(得分:0)

假设只有一条记录的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
;

with CustomerReport (CustomerNo, ViewCount) as 
     (SELECT t.CustomerNo, Sum(t.ViewCount) ViewCount 
        FROM #Temp t
       GROUP BY t.CustomerNo)
Select q1.CustomerNo, q1.ViewCount 
       , (Select ImagePath
            from #Temp
           where #Temp.CustomerNo = q1.CustomerNo
             and #Temp.IsDefault = 1) ImgPath
  from CustomerReport q1
;

drop table #temp
;

AFAIK,您需要MS-SQL 2008+才能获得对CTE语法的支持。