使用MSSQL GROUP BY列太多

时间:2015-09-21 07:21:34

标签: php sql-server

如何在我的查询中使用分组依据到我的 LOCATION 列,这让我认为是汇总的事情?

SELECT a.[PlateNo]
,a.[TrxDate] as DATES
,a.[Location] ,a.[account]
,a.[TrxTime]
,a.[Msg]
,b.company FROM [Mark_Fast].[dbo].[Alarm] a
inner join [Mark_Fast].[dbo].[account] b 
on a.[account] = b.senderno or a.[account] = b.sim1 
where a.trxdate BETWEEN '09/10/2015' AND '09/10/2015' and Msg LIKE '%geo%' 
and (a.PlateNo = 'BCY536') ORDER BY Location desc

示例输出为:

PlateNo  Dates    Location   account   TrxTime          Msg             company
123     9/9/1999   Loc 1      321      02:39:00  Geozone Exit Alert!    Transpartner Trucking Services
123     9/9/1999   Loc 1      321      02:39:00  Geozone Exit Alert!    Transpartner Trucking Services
123     9/9/1999   Loc 1      321      02:31:00  Geozone Entry Alert!   Transpartner Trucking Services
123     9/9/1999   Loc 3      321      02:32:00  Geozone Exit Alert!    Transpartner Trucking Services
123     9/9/1999   Loc 3      321      02:33:00  Geozone Exit Alert!    Transpartner Trucking Services
123     9/9/1999   Loc 1      321      02:34:00  Geozone Entry Alert!   Transpartner Trucking Services
123     9/9/1999   Loc 2      321      02:35:00  Geozone Exit Alert!    Transpartner Trucking Services
123     9/9/1999   Loc 2      321      02:37:00  Geozone Entry Alert!   Transpartner Trucking Services

我希望输出为 Location 分组,但我不知道如何在查询中执行它。我想要实现的是输出如下:

PlateNo  Dates    Location   account   TrxTime          Msg             company
        123     9/9/1999   Loc 1      321      02:39:00  Geozone Exit Alert!    Transpartner Trucking Services
        123     9/9/1999   Loc 2      321      02:39:00  Geozone Exit Alert!    Transpartner Trucking Services
        123     9/9/1999   Loc 3      321      02:31:00  Geozone Exit Alert! Transpartner Trucking Services

3 个答案:

答案 0 :(得分:0)

如果您希望按位置查看帐户汇总,则必须在查询中添加以下内容。

GROUP BY a.Location HAVING sum(a.accounts)

如果您可以提供所有列标题的预期输出样本,您可能会得到更好的答案。

对于最新的TrxTime,您需要在查询中添加以下行

GROUP BY a.Location HAVING max(a.TrxTime)

答案 1 :(得分:0)

尝试使用聚合函数MAX():

SELECT a.[PlateNo], a.[TrxDate] as DATES, a.[Location], a.[account], MAX(a.[TrxTime]), a.[Msg], b.company FROM [Mark_Fast].[dbo].[Alarm] a INNER JOIN [Mark_Fast].[dbo].[account] b ON a.[account] = b.senderno or a.[account] = b.sim1 WHERE a.trxdate BETWEEN '09/10/2015' AND '09/10/2015' AND Msg LIKE '%geo%' AND (a.PlateNo = 'BCY536') GROUP BY a.[PlateNo],a.[TrxDate],a.[Location],a.[account],a.[Msg],b.company

答案 2 :(得分:0)

仅按位置进行分组不会,因为其他列的数据不同。

因此,您必须添加更多列才能唯一地显示记录。 GROUP BY [Location],[TrxDate],[TrxTime],[Msg]