这是我的SQL语句
select id , name, type, value from table1 a
INNER JOIN table2 b on a.id = b.id
where b.type in ('display','contact','ship')
产生以下结果的
ID name type value
5 test display display1
5 test contact contact1
5 test ship ship1
6 test2 display display2
6 test2 contact contact2
6 test2 ship ship2
我需要以这种
的方式获得结果id name display contact ship
5 test display1 contact1 ship1
6 test2 display2 contact2 ship2
我尝试了这个解决方案:https://stackoverflow.com/a/6849706/2645738,但它给了我相同的结果(每个数据3行)。这就像我需要按ID和名称分组,但不知道如何以列显示,联系和发布。
请你帮助我。
答案 0 :(得分:4)
有必要使用PIVOT
您也可以使用简单的case
表达式
SELECT ID,
Name,
MAX(CASE([type]) WHEN 'display' THEN value END) [display],
MAX(CASE([type]) WHEN 'contact' THEN value END) [contact],
MAX(CASE([type]) WHEN 'ship' THEN value END) [ship]
FROM <table> GROUP BY ID, Name
结果:
ID Name display contact ship
5 test display1 contact1 ship1
6 test2 display2 contact2 ship2
答案 1 :(得分:2)
此查询应该为您提供所需的结果:
select a.id , a.name,
max(case when b.type = 'display' then value end) as display,
max(case when b.type = 'contact' then value end) as contact,
max(case when b.type = 'ship' then value end) as ship
from table1 a
INNER JOIN table2 b on a.id = b.id
where b.type in ('display','contact','ship')
group by a.id, a.name
答案 2 :(得分:2)
这为我工作
WITH T
AS
(
SELECT
id ,
name,
type,
value
FROM table1 a
INNER JOIN table2 b
ON a.id = b.id
WHERE b.type in ('display','contact','ship')
)
SELECT
*
FROM T
PIVOT
(
MAX([Value])
FOR
[Type] IN
(
[display],[Contact],[Ship]
)
)PVT
答案 3 :(得分:2)
如果您需要PIVOT
:
DECLARE @DataSource TABLE
(
[id] TINYINT
,[name] VARCHAR(12)
,[type] VARCHAR(12)
,[value] VARCHAR(12)
);
INSERT INTO @DataSource ([id], [name], [type], [value])
VALUES (5, 'test', 'display', 'display1')
,(5, 'test', 'contact', 'contact1')
,(5, 'test', 'ship', 'ship1')
,(6, 'test2', 'display', 'display2')
,(6, 'test2', 'contact', 'contact2')
,(6, 'test2', 'ship', 'ship2');
SELECT *
FROM @DataSource
PIVOT
(
MAX([value]) FOR [type] IN ([display], [contact], [ship])
) PVT;
答案 4 :(得分:0)
var n interface{} = 2
var pn = &n
var pf = (*int64)(unsafe.Pointer(pn))
fmt.Println(pf)
fmt.Println(pn)
fmt.Println(*pn) // 2
fmt.Println(*pf) // not 2
*pf = 9
fmt.Println(*pn) //error invalid memory address or nil pointer dereference
fmt.Println(*pf) // 9