简体   繁体   English

从查询中删除重复项

[英]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) 我试过使用distinct和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 : 您可以将派生表用于JOINReaderData ,以便在JOIN之前删除重复项:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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