gpt4 book ai didi

sql-server - 比较两行并识别值不同的列

转载 作者:行者123 更新时间:2023-12-02 19:21:07 24 4
gpt4 key购买 nike

情况

我们有一个应用程序,我们将机器设置存储在 SQL 表中。当用户更改机器的参数时,我们创建一个“修订版”,这意味着我们在表中插入一行。该表大约有 200 个。在我们的应用程序中,用户可以查看每个修订版。

问题

我们想要突出显示自上次修订以来已更改的参数。

问题

是否有仅 SQL 的方法来获取两行之间差异的列名称?

示例

ID | p_x | p_y | p_z
--------------------
11 | xxx | yyy | zzz

12 | xxy | yyy | zzy

查询应返回 p_xp_z

编辑

该表有 200 列,而不是行...

我的出路

我的目的是找到一个“单行 SQL 语句”来解决这个问题。

我在下面的答案中看到,这是 SQL 中的一个更大的事情。由于这个问题没有简短的、包含 SQL 的解决方案,因此在我们的软件后端(c#)解决它当然要容易得多!

但是,由于这不是我的问题的真正“答案”,因此我不会将其标记为已回答。

感谢您的帮助。

最佳答案

你说:

 We want to highlight the parameters that have changed since the last revision.

这意味着您希望显示(或报告)使更改的参数脱颖而出。

如果您无论如何都要显示所有参数,那么在前端以编程方式执行此操作会容易得多。对于编程语言来说,这将是一个简单得多的问题。不幸的是,不知道你的前端是什么,我无法给你具体的建议。

如果您确实无法在前端执行此操作,但必须在数据库查询中接收此信息(您确实说过“仅 SQL”),则需要指定您想要的数据格式in. 两条记录之间更改的列的单列列表?带有标志的列列表,指示哪些列已更改或未更改?

但这里有一种可行的方法,尽管在此过程中它会在进行比较之前将所有字段转换为 nvarchar:

  1. 使用描述的技术 here (免责声明:这是我的博客)将您的记录转换为 ID-名称-值对。
  2. 将结果数据集与 ID 上的自身连接起来,以便您可以比较这些值并打印已更改的值:

     with A as (    
    -- We're going to return the product ID, plus an XML version of the
    -- entire record.
    select ID
    , (
    Select *
    from myTable
    where ID = pp.ID
    for xml auto, type) as X
    from myTable pp )
    , B as (
    -- We're going to run an Xml query against the XML field, and transform it
    -- into a series of name-value pairs. But X2 will still be a single XML
    -- field, associated with this ID.
    select Id
    , X.query(
    'for $f in myTable/@*
    return
    <data name="{ local-name($f) }" value="{ data($f) }" />
    ')
    as X2 from A
    )
    , C as (
    -- We're going to run the Nodes function against the X2 field, splitting
    -- our list of "data" elements into individual nodes. We will then use
    -- the Value function to extract the name and value.
    select B.ID as ID
    , norm.data.value('@name', 'nvarchar(max)') as Name
    , norm.data.value('@value', 'nvarchar(max)') as Value
    from B cross apply B.X2.nodes('/myTable') as norm(data))

    -- Select our results.

    select *
    from ( select * from C where ID = 123) C1
    full outer join ( select * from C where ID = 345) C2
    on C1.Name = c2.Name
    where c1.Value <> c2.Value
    or not (c1.Value is null and c2.Value is null)

关于sql-server - 比较两行并识别值不同的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28194628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com