0

我正在尝试使用可变时间间隔和目的地选择从两个表中获取数据(T_Stamp、Destination、Weight、Line)。这将进入点火 SCADA。下面的我的 SQL 代码适用于大多数情况,除非两个表中的条目具有相同的时间戳。在这些情况下,它只显示表 A 中的数据。这给了我不正确目的地的结果。我知道 COALESCE 函数返回第一个非空值,但我不知道如何编写这个逻辑。

SELECT COALESCE(a.t_stamp, b.t_Stamp) T_Stamp, COALESCE(a.Destination, b.Destination) Destination, COALESCE(a.A_Weight, b.B_Weight) Weight, CASE WHEN a.Ham_Line_A_Counts_ndx > 0 THEN 'A' ELSE 'B' END AS Line
FROM Ham_Line_A_Counts as a FULL OUTER JOIN 
     b_Counts AS b
      ON a.t_Stamp=b.t_Stamp
WHERE (a.t_Stamp Between '{Root Container.Popup Calendar.date}' AND '{Root Container.Popup Calendar 1.date}' AND a.Destination = {Root Container.Dropdown 1.selectedValue}) OR (b.t_Stamp Between '{Root Container.Popup Calendar.date}' AND '{Root Container.Popup Calendar 1.date}' AND b.Destination = {Root Container.Dropdown 1.selectedValue})
ORDER BY T_Stamp DESC

预期成绩:

t_stamp 目的地 重量 线
10:05:01 1 30.01 一种
10:05:05 1 25.11
10:05:07 1 26.32

实际结果:

t_stamp 目的地 重量 线
10:05:01 1 30.01 一种
10:05:05 1 25.11
10:05:07 2 25.46 一种

样本数据表 A:| t_stamp | 目的地 | A_重量 | | -------- | ------------ | -------- | | 10:05:01 | 1 | 30.01 | | 10:05:07 | 2 | 32.32 |

表 B:| t_stamp | 目的地 | B_重量 | | -------- | ------------ | -------- | | 10:05:03 | 1 | 24.01 | | 10:05:07 | 1 | 26.46 |

4

1 回答 1

0

我怀疑您想要的是类似于以下内容的内容,它使用 aUNION而不是 a JOIN

SELECT a.t_stamp T_Stamp, a.Destination Destination, a.A_Weight Weight, 'A' Line
FROM Ham_Line_A_Counts a
WHERE a.t_Stamp Between '{Root Container.Popup Calendar.date}' AND '{Root Container.Popup Calendar 1.date}' AND a.Destination = {Root Container.Dropdown 1.selectedValue}
UNION ALL
SELECT b.t_stamp T_Stamp, b.Destination Destination, b.B_Weight Weight, 'B' Line
FROM b_Counts b
WHERE b.t_Stamp Between '{Root Container.Popup Calendar.date}' AND '{Root Container.Popup Calendar 1.date}' AND b.Destination = {Root Container.Dropdown 1.selectedValue})
ORDER BY T_Stamp DESC

这会从a正确的目的地和时间戳获取结果,从正确的目的地和时间戳获取结果b,然后按时间戳对它们进行排序。因此,如果时间戳位于aand中b,则两行将依次返回。我使用UNION ALL的不仅仅是UNION因为列中的硬编码'A'/'B'Line意味着不会有重复,并且UNION ALL可能更有效。

于 2021-04-08T18:50:48.833 回答