如何从表行值创建视图

时间:2016-06-16 13:35:01

标签: sql sql-server-2008

我有一张这样的表:

ID  |  staff_id  |  Meta_key  | Meta_Value  | Meta_Group
1          1         landline      456          contact
2          1          mobile       777          contact
3          1          email      i@i.i          contact
4          2         landline      453          contact
5          2          mobile       888          contact
6          2          email      d@i.i          contact

我想创建一个名为view_contact_details的视图,如下所示:

 staff_id  |  landline  |  mobile  | email
    1          456          777      i@i.i
    2          453          888      d@i.i

这可能吗?我感谢任何帮助,并提前感谢你。

1 个答案:

答案 0 :(得分:1)

您可以使用包裹在MAX

中的CASE执行此操作

样本数据

CREATE TABLE #TestData (ID int, staff_id int, meta_key varchar(10), meta_value varchar(10), meta_group varchar(10))
INSERT INTO #TestData (ID, staff_id, meta_key, meta_value, meta_group)
VALUES
(1,1,'landline','456','contact')
,(2,1,'mobile','777','contact')
,(3,1,'email','i@i.i','contact')
,(4,2,'landline','453','contact')
,(5,2,'mobile','888','contact')
,(6,2,'email','d@i.i','contact')

查询;

CREATE VIEW view_contact_details
AS
SELECT
Staff_ID
,MAX(CASE WHEN Meta_Key = 'landline' THEN Meta_Value END) Landline
,MAX(CASE WHEN Meta_Key = 'mobile' THEN Meta_Value END) Mobile
,MAX(CASE WHEN Meta_Key = 'email' THEN Meta_Value END) Email
FROM #TestData
GROUP BY staff_id

结果;

Staff_ID    Landline    Mobile  Email
1           456         777     i@i.i
2           453         888     d@i.i