【问题标题】:MSSQL COALESCE function with multiple non null values具有多个非空值的 MSSQL COALESCE 函数
【发布时间】:2021-07-04 14:59:47
【问题描述】:

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

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 Destination Weight Line
10:05:01 1 30.01 A
10:05:05 1 25.11 B
10:05:07 1 26.32 B

实际结果:

t_stamp Destination Weight Line
10:05:01 1 30.01 A
10:05:05 1 25.11 B
10:05:07 2 25.46 A

样本数据 表 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 |

【问题讨论】:

  • 使用wherefull join 真的很棘手。你确定你需要full join吗?示例数据和清晰的逻辑描述会有所帮助。
  • 感谢您的回复@GordonLinoff 我目前有两张桌子。表 A 具有列:t_stamp、Destination 和 A_Weight;表 B 具有列:t_stamp、Destination 和 B_Weight 我正在尝试使用 t_stamp 的“Where”语句和目标列。在某些情况下,我会在两个表中输入具有相同 t_stamp 值的条目,这会导致我的“Coalesce”语句仅从 A 列中选择值,而不管它是否具有正确的目标值。我应该使用不同类型的 Join 吗?
  • 您需要提供样本数据
  • 所有与问题直接相关的细节都可以通过问题下方的edit链接添加。直接从问题中获取所有输入会更有用,而不是通过阅读所有 cmets。
  • 如果两个表中都有一条时间戳相同的记录怎么办?如果您想要 B 而不是 A,您可以颠倒 COALESCE 的顺序(如前一条评论中所述)。如果你想要两行,那么这可能应该是某种UNION,而不是JOIN

标签: sql sql-server coalesce ignition


【解决方案1】:

我怀疑您想要的是类似于以下内容的内容,它使用 UNION 而不是 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 获取具有正确目的地和时间戳的结果,然后按时间戳对它们进行排序。因此,如果时间戳位于ab 中,则这两行将依次返回。我使用了UNION ALL 而不仅仅是UNION,因为Line 列中的硬编码'A'/'B' 意味着不会有重复,而UNION ALL 可能更有效。

【讨论】:

  • 谢谢!这正是我所需要的。我之前尝试过 UNION ALL 并没有返回任何结果。现在我发现我使用不正确。我很少将 SQL 用作控制工程师,并且仍在学习中。感谢大家的帮助。
猜你喜欢
  • 1970-01-01
  • 2015-09-13
  • 1970-01-01
  • 2021-10-06
  • 2019-09-06
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多