表格结构
EID COLA COLB
1 name A
1 age 23
1 city hyd
1 email abc@live.in
1 mobile 45126
2 name B
2 age 43
2 city bang
3 name C
3 age 13
3 city bang
3 email jdf@live.in
我想输出如下
ID||COLA||COLB
1||name||A
1||age||23
1||city||hyd
1||email||abc@live.in
1||mobile||45126
2||name||B
2||age||43
2||city||bang
2||email||NULL
2||mobile||NULL
3||name||C
3||age||13
3||city||bang
3||email||jdf@live.in
3||mobile||NULL
请您告诉我如何实现此输出。 如何显示缺少任何必填字段(名称,年龄,城市,电子邮件,移动设备)的结果,然后它应该显示为该字段为Null,在我们将在where子句中通过过滤单个id值的查询中显示和可乐(姓名,年龄,城市,电子邮件,手机)
我的查询:
select
case colA
when cola then colA+'||'+colB
end
from tbl
where cola in ('name','age','city','email','mobile')
答案 0 :(得分:0)
首先让我说,如果您的表格结构需要name
,age
,city
等列,那么您要求的内容会非常简单。名称值对不是对于这样的表格来说,这是一个很好的设计,更不用说严重的性能问题会困扰任何解决这种结构的问题。
话虽如此,您可以使用PIVOT
/ UNPIVOT
或属性表(包含所需属性列表的表)和GROUP BY
与CROSS JOIN
。
示例数据
DECLARE @table1 TABLE(
EID INT, COLA VARCHAR(30), COLB VARCHAR(30) )
INSERT INTO @table1 VALUES
(1,'name','A'),
(1,'age','23'),
(1,'city','hyd'),
(1,'email','abc@live.in'),
(1,'mobile','45126'),
(2,'name','B'),
(2,'age','43'),
(2,'city','bang'),
(3,'name','C'),
(3,'age','13'),
(3,'city','bang'),
(3,'email','jdf@live.in');
使用PIVOT / UNPIVOT
SELECT EID, COLA,NULLIF(COLB,'') COLB
FROM
(
SELECT EID,ISNULL([name],'') name,ISNULL([age],'') [age],ISNULL([city],'') [city],ISNULL([email],'') [email],ISNULL([mobile],'') [mobile]
FROM (SELECT EID,COLA,COLB
FROM @table1) T
PIVOT ( MAX(COLB) FOR COLA IN ( [name],[age],[city],[email],[mobile] ) ) AS pvt
) tbl
UNPIVOT (COLB FOR ColA IN (name,age,city,email,mobile)) AS Upvt
请注意,我使用的是ISNULL(col,'')
,因为UNPIVOT
排除了NULL
值。如果''
是您的有效值,则可以使用其他字符串来表示NULL
或使用GROUP BY
解决方案。
使用属性表进行查询,GROUP BY
与CROSS JOIN
进行查询
;WITH Cols(Name) AS
(
SELECT 'name' UNION ALL SELECT 'age' UNION ALL SELECT 'city' UNION ALL SELECT 'email' UNION ALL SELECT 'mobile'
)
SELECT t.EID,C.Name,t1.COLB
FROM
(
SELECT EID
FROM @table1
GROUP BY EID
) t
CROSS JOIN Cols c
LEFT JOIN @table1 t1 ON t1.EID = t.EID and t1.COLA = C.Name
答案 1 :(得分:0)
CREATE TABLE DesireOutput(EID nvarchar(10),COLA NVARCHAR(10),COLB nvarchar(50))
插入DesireOutput VALUES('1','name','A')
插入DesireOutput值('1','年龄','23')
插入DesireOutput VALUES('1','city','hyd')
插入DesireOutput VALUES('1','email','abc@live.IN')
插入DesireOutput VALUES('1','mobile','45126')
插入DesireOutput VALUES('2','name','B')
插入DesireOutput值('2','年龄','43')
插入DesireOutput VALUES('2','city','bang')
插入DesireOutput VALUES('3','name','C')
插入DesireOutput值('3','年龄','13')
插入DesireOutput VALUES('3','city','bang')
插入DesireOutput VALUES('3','email','jdf@live.IN')
DECLARE @t AS TABLE ( ColA NVARCHAR(50) )
INSERT INTO @t
SELECT DISTINCT
D.COLA
FROM DesireOutput D
SELECT t.EID , c.ColA , t1.COLB FROM ( SELECT
EID FROM DesireOutput GROUP BY EID
) t
CROSS JOIN @t c
LEFT JOIN DesireOutput t1 ON t1.EID = t.EID
AND t1.COLA = c.ColA ORDER BY EID