我有一张表格,其中包含ticket_id's
,field_id's
和值。
例如
ticket_id field_id value 1001 1 Peter 1002 1 Dave 1001 2 555-2565 1002 2 554-2548
我的目标是尝试编写一个将在同一个表中水平显示值的查询。例如
Ticket_ID Field1 Field2 1001 Peter 555-2565 1002 Dave 554-2548
有很多field_ids
。我尝试过使用rownumber()
,但它没有用。
有什么想法吗?
答案 0 :(得分:2)
Select Temp_field1.ticket_id,Field1,Field2
From
(Select ticket_id,value as Field1 from table where field_id = 1) as Temp_field1,
(Select ticket_id,value as Field2 from table where field_id = 2) as Temp_field2
Where Temp_field1.ticket_id = Temp_field2.ticket_id;
答案 1 :(得分:1)
SELECT TICKET_ID, MAX(FIELD_1),MAX(FIELD_2)
FROM (
SELECT TICKET_ID, CASE field_id
WHEN 1 THEN VALUE
ELSE NULL end AS FIELD_1,CASE field_id
WHEN 2 THEN VALUE
ELSE NULL end AS FIELD_2)
GROUP BY FIELD_1,FIELD_2
这有点古怪,但我尽量减少选择。 我们的想法是在不需要值时将null设置为null 当我们执行MAX时,它将取非空值(MAX适用于VARCHAR)
答案 2 :(得分:0)
答案 3 :(得分:0)
这是一个选项。如果有很多field_ids
,请不要了解效果。
SELECT t1.`ticket_id` AS Ticket_ID, t1.`value` AS Field1, t2.`value` AS Field2 FROM `ticket` t1
LEFT JOIN `ticket` t2 ON t1.`ticket_id` = t2.`ticket_id`
WHERE t1.`value` != t2.`value`
GROUP BY t1.`ticket_id`