【问题标题】:How to get column records into row in my case using SQL Server?在我的情况下,如何使用 SQL Server 将列记录放入行中?
【发布时间】:2018-02-19 02:17:27
【问题描述】:

我有一个名为 RelationData 的表,它有 4 列:

关系数据

Parent    child1    child2    child3
------------------------------------
111       112       113       117
111       222       223       224
444       441       442       443 

如果任何 ID 中的每一个都匹配,我想在一行中显示。

如果用户搜索 111 或 112 或 113 或 117 或 222 或 223 或 224,它必须显示

111
112
113 
117
222
223
224   

如果用户搜索442,结果应该是

444
441
442
443 

即使我使用case,它也会按列显示,而不是按行显示

【问题讨论】:

    标签: sql sql-server join stored-procedures


    【解决方案1】:

    您可以取消透视结果。这是一种方法:

    select v.child
    from relationdata rd outer apply
         (values (rd.child1), (rd.child2), (rd.child3), (rd.child4)) v(child)
    where 111 in (rd.child1, rd.child2, rd.child3, rd.child4);
    

    注意:有四列带有这样的引用通常表示数据库设计不佳。最好有一个包含单个 child 列和“子编号”的关系表。

    【讨论】:

    • 如何消除NULL
    • @mohamedfaiz 。 . .将and v.child is not null 添加到where 子句中。
    • @mohamedfaiz 在 WHERE 子句中添加“AND v.Child IS NOT NULL”。
    • @GordonLinoff 谢谢兄弟。 5分钟后我会接受你的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多