如何使用窗口功能更新表中的列

时间:2019-07-02 07:43:24

标签: sql sql-update mariadb window-functions

我在MariaDB中有一个带有不同节点的表,每个节点可以具有多个硬件组件,我想计算每个节点有多少硬件组件并将其存储在列中。

因此,我创建了一个空列,称为“ HW_Count”。我可以通过以下SELECT语句进行此计算。

SELECT NodeID,COUNT(NodeId) OVER (PARTITION BY NodeId) FROM Hardware AS HW_Count

这将返回以下类型的列表

 NodeID    HWCount
   1         33
   1         33
  ...        ...
   2         11
   2         11
  ...        ...

现在,我想用tihs信息更新表Hardware中的空列,但是我不确定如何编写正确的UPDATE语句。我想按部就班

UPDATE Hardware   
SET HW_count = 
COUNT(NodeId) OVER (PARTITION BY NodeId)

但是它返回

"SQL ERROR (4015): Window function is allowed only in SELECT list and ORDER BY clause". 

更新专栏的正确方法是什么?

谢谢!

3 个答案:

答案 0 :(得分:0)

我设法找到了答案

UPDATE Hardware, (SELECT NodeID,COUNT(NodeID) AS `HW_Count`  FROM 
Hardware GROUP BY NodeID) AS dummyTable
SET Hardware.hw_count = Dummytable.Hw_count
WHERE Hardware.NodeID= dummytable.NodeID

答案 1 :(得分:0)

请尝试以下操作:

UPDATE H1
SET HW_count = (SELECT COUNT(*) HW_count FROM Hardware WHERE NodeID = H1.NodeID GROUP BY NodeID)
FROM Hardware H1
    INNER JOIN Hardware H2 ON H1.NodeID=H2.NodeID

答案 2 :(得分:0)

我建议使用JOINGROUP BY进行此操作:

UPDATE Hardware h JOIN
       (SELECT NodeID, COUNT(NodeID) AS new_hw_count
        FROM Hardware
        GROUP BY NodeID
       ) hh
       ON hh.NodeID = h.NodeID
    SET h.hw_count = h.new_hw_count;