我想考虑制作以下内容的可能性:
create table customers
(
ID int identity,
name varchar(50)
)
create table additional
(
ID int identity,
customer_id int references customers(ID),
input_name varchar(50),
input_value varchar(50)
)
应该能够为特定客户定义附加输入的名称和值,并将其显示在列中。例如:
insert into customers (name) values ("aaa");
insert into additional (customer_id,input_name,input_value) values (1,"last name","bbb");
现在我需要的结果是:
customerID | first name | last name
-----------------------------------
1 | aaa | bbb
以便将其他字段显示为列名。
答案 0 :(得分:2)
如果您对静态查询感到满意,这很容易:
SELECT c.customerID, a2.input_value AS first_name, a1.input_value AS last_name
FROM customers c
LEFT JOIN additional a1 ON a1.ID = c.ID and a1.input_name = 'last name'
LEFT JOIN additional a2 ON a2.ID = c.ID and a2.input_name = 'first name'
如果您对静态查询不满意,这意味着列的数量和名称将随数据而变化。因此,在这种情况下,您必须动态构建查询。