分组时获取其他列

时间:2019-07-03 02:42:27

标签: sql sql-server sql-server-2008

我正尝试在此搜索中再添加一列,但是当我添加下一列时会产生多行内容

下面的代码可以带回正确的信息,但是我需要名为category的列,而不必为每个总线带回多行

and the structure of **rqaforgeolocsource**

str(rqaforgeolocsource)
Classes ‘data.table’ and 'data.frame':  365 obs. of  7 variables:
 $ sidentity    : chr  "10265(alpha)" "10265(alpha)" "10265(alpha)" "10265(alpha)" ...
 $ TA           : int  112 99 123 97 111 121 124 129 128 126 ...
 $ lon          : num  82.4 82.4 82.4 82.4 82.4 ...
 $ lat          : num  26 26 26 26 26 ...
 $ az           : int  120 120 120 120 120 120 120 120 120 120 ...
 $ distance     : int  8736 7722 9594 7566 8658 9438 9672 10062 9984 9828 ...
 $ slocationzone:List of 365
  ..$ :sfc_POLYGON of length 1; first list element: List of 1
  .. ..$ : num [1:510, 1:2] 82.5 82.5 82.5 82.5 82.5 ...
  .. ..- attr(*, "class")= chr  "XY" "POLYGON" "sfg"
  ..$ :sfc_POLYGON of length 1; first list element: List of 1
  .. ..$ : num [1:510, 1:2] 82.5 82.5 82.5 82.5 82.5 ...
  .. ..- attr(*, "class")= chr  "XY" "POLYGON" "sfg"

我希望在每个里程数旁边都看到一个类别,例如在公交108的第一个回程上看到A。但是,当我将类别添加到搜索中时,我会得到5辆公交108。

2 个答案:

答案 0 :(得分:0)

只需使用聚合函数:

SELECT wo.bus,  MAX(wo.service_date) AS ServiceDate, MAX(wo.mileage) AS Mileage,
       MAX(wo.category) as category
FROM dbo.WorkOrders wo
WHERE wo.type = 'PMI'
GROUP BY wo.bus
ORDER BY wo.bus

答案 1 :(得分:0)

在分组依据中添加类别,并使用row_number依次添加行ID。

   /****** Script for SelectTopNRows command from SSMS  ******/
select 
    *
from
(
    SELECT [bus]
          ,[Category]
          ,max([Servicedate]) as [Servicedate]
          ,max([mileage]) as [mileage]
            , ROW_NUMBER() OVER (PARTITION BY [bus] ORDER BY max([mileage]) desc) rowID
      FROM [tbltest]
  group by bus, category
) tmp
where tmp.rowID = 1