按两列分组但仅显示一列

时间:2017-09-18 13:06:16

标签: sql sql-server sql-server-2014

我正在运行以下脚本。

select PlateID1, PlateID2, Max(TimeStamp) as LastVisit, Min(TimeStamp) as FirstVisit,
       count(PlateID1) as VisitCount
from ActivityLog
where (TimeStamp > '9/15/2017 12:00:00 AM' and TimeStamp < '9/18/2017 12:00:00 AM')
group by PlateID1, PlateID2
having  count(PlateID1) > 1
order BY VisitCount desc

返回以下结果:

PlateID1  PlateID2  LastVisit                 FirstVisit               VisitCount
7BAY665   _blank_   2017-09-15 19:28:20.457   2017-09-15 13:24:25.770  3621
_blank_   _blank_   2017-09-17 15:48:48.753   2017-09-15 12:55:46.557  305
7BAY665   7BAY665   2017-09-15 19:26:26.040   2017-09-15 19:05:21.627  5
7BAY665   _blank_   2017-09-15 19:17:03.170  2017-09-15 19:16:41.943   2

我需要省略空白,并将PlateID1和PlateID2的结果组合在一起。因此,每当PlateID1或PlateID2中的板重复时,我需要对其进行分组/计数。

我想要的结果,再次,抱歉格式不佳应该是这样的。

   PlateID  LastVisit                 FirstVisit               VisitCount
   7BAY665 2017-09-15 19:28:20.457    2017-09-15 13:24:25.770  3628

根据Tab的评论,我提出了以下解决方案。谢谢!

SELECT t1.plateid, 
       Max(t1.timestamp) AS LastVisit, 
       Min(timestamp)    AS FirstVisit, 
       Count(plateid)    AS VisitCount 
FROM   ((SELECT plateid1 AS PlateID, 
                timestamp 
         FROM   activitylog 
         WHERE  ( timestamp > '9/15/2017 12:00:00 AM' 
                  AND timestamp < '9/18/2017 12:00:00 AM' ) 
                AND plateid1 IS NOT NULL 
                AND plateid1 <> '') 
        UNION 
        (SELECT plateid2 AS PlateID, 
                timestamp 
         FROM   activitylog 
         WHERE  ( timestamp > '9/15/2017 12:00:00 AM' 
                  AND timestamp < '9/18/2017 12:00:00 AM' ) 
                AND plateid2 IS NOT NULL 
                AND plateid2 <> '')) AS t1 
GROUP  BY t1.plateid 
HAVING Count(plateid) > 1 

2 个答案:

答案 0 :(得分:0)

在CTE或派生表中,UNION ALL有两个查询。在第一个选择PlateID1作为PlateID,在第二个中选择PlateID2作为PlateID。在两个查询中,包括您当前显示的所有其他列。使用WHERE子句来消除NULL /空PlateID。

然后使用当前查询从CTE中选择SELECT和GROUP BY PlateID。

答案 1 :(得分:0)

您可以尝试使用coalesce

select COALESCE(PlateID1, PlateID2) PlateID, 
       Max(TimeStamp) as LastVisit, 
       Min(TimeStamp) as FirstVisit,
       count(PlateID1) as VisitCount
from ActivityLog
where (TimeStamp > '9/15/2017 12:00:00 AM' and TimeStamp < '9/18/2017 12:00:00 AM')
AND PlateID1 IS NOT NULL AND PlateID2 IS NOT NULL
group by COALESCE(PlateID1, PlateID2)
having  count(PlateID1) > 1
order BY VisitCount desc