简体   繁体   中英

Removing duplicates from query

i have the query below that is getting the percentage time that a device is on throughout the day, however as there are duplicates in the data that i cant easily get rid off, what would be the best way to do this?

I have tried using distinct and Max(dtReading)

    SELECT DISTINCT
  workStationNo,
  controllerID,

  CAST(DATEPART(DAY, DATEADD(DAY, DATEDIFF(DAY, 0, MAX(dtReading)), 0)) AS varchar) AS date,
  (CAST(COUNT(*) AS float(1)) / CAST((DATEPART(HOUR, GETDATE()) * 30) AS float(1)) * CAST(100 AS float(1))) AS dayPercentage

FROM Controller
INNER JOIN ManufacturingLayout
  ON Controller.machID = ManufacturingLayout.workStationID
INNER JOIN ReaderData
  ON Controller.ctrlID = ReaderData.controllerID

WHERE dtReading >= CONVERT(datetime, '09/05/2018', 103)
AND dtReading <= DATEADD(HOUR, 24, CONVERT(datetime, '16/05/2018 23:59:59', 103))
AND (EventType = '(0x05)Open switch')
GROUP BY controllerID,
         DATEADD(DAY, DATEDIFF(DAY, 0, dtReading), 0),
         workStationNo
ORDER BY 1, 2

Query output

Workstation no controllerID  date dayPercentage
ZW01006            38         15    80.20833
ZW01006            38         16    142.0833
ZW01007            30         15    62.5
ZW01007            30         16    120.2083
ZW01008            31         15    92.70833
ZW01008            31         16    141.0417
ZW01010            40         15    0.625

source data

workStationNo   controllerID    dtReading
ZW01007            30           2018-05-16 15:42:39.000
ZW01007            30           2018-05-16 15:42:38.000
ZW01007            30           2018-05-16 15:40:38.000    <- duplicate
ZW01007            30           2018-05-16 15:40:38.000    <- duplicate 
ZW01007            30           2018-05-16 15:38:37.000
ZW01007            30           2018-05-16 15:38:37.000
ZW01007            30           2018-05-16 15:36:37.000
ZW01007            30           2018-05-16 15:36:37.000
ZW01007            30           2018-05-16 15:34:36.000

You could use a derived table for your JOIN to ReaderData , in order to remove duplicates before the JOIN :

...
INNER JOIN (SELECT DISTINCT controllerID, dtReading
            FROM ReaderData) ReaderData
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM