SQL Server - 将名称值对显示为列?

时间:2017-10-07 09:07:43

标签: sql-server json

我有如下表格:

CREATE TABLE case_form 
(
    id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    title VARCHAR(50) NOT NULL,
    description TEXT NOT NULL,
    PRIMARY KEY (id)
)

INSERT INTO case_form (id, title, description)
VALUES (1, 'test', 'test')

CREATE TABLE case_fields 
(
    id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    value TEXT NOT NULL,
    case_form_id INT(10) UNSIGNED NOT NULL,
    PRIMARY KEY (id),
    INDEX FK__case_form (case_form_id),
    CONSTRAINT FK_case_form FOREIGN KEY (case_form_id) REFERENCES case_form 
)

INSERT INTO case_fields (name, value, case_form_id)
VALUES ('type', 'Request', 1), ('category', 'Sales', 1)

我想创建一个视图或为case_form表生成一个查询,该查询将包含所有名称值对作为列,如下所示:

id  | title | description | type    | category
----+-------+-------------+---------+------------
1   | test  |  test       | Request | Sales

以下查询未提供上述输出,但提供以下内容:

select t1.*, t2.name, t2.value 
from case_form t1
inner join case_fields t2 on t2.case_form_id = t1.id

输出:

id  | title | description | name    | value
----+-------+-------------+---------+---------
1   | test  |  test       | type    | Request
1   | test  |  test       | category| Sales

我是否可能将名称值对作为json对象存储在case_form表中,如下所示:

{ 
  type: "Request",
  category: "Sales",
  team: "abc"
}

我如何查询这个给我一个类似于上面的表格视图?

这种结构的原因是我可以在.Net MVC应用程序中创建动态表单

任何帮助提示指导赞赏

1 个答案:

答案 0 :(得分:0)

您基本上需要pivot数据。下面的查询给出了你提到的结果:

select * from 
(select t1.id, t1.title, CAST(t1.description as VARCHAR(MAX)) as [description], CAST(t2.name as VARCHAR(MAX)) as Name, CAST(t2.value as VARCHAR(MAX)) as value
from 
case_form t1
inner join case_fields t2 on t2.case_form_id = t1.id
) as t
pivot
( max(value)
for name in ([type],[category])
)as piv