SQL从表中添加额外的列

时间:2018-10-09 12:35:12

标签: mysql sql

我环顾了网上,但是SQL对我来说是新的,因此由于所有复杂的连接等原因,我无法使用正确的语法。我将如何实现以下目标:

SELECT 
event.Id, 
event.Name, 
event.Date,
event.Size,  
event.Email,  
verificationdata.Value,

/*I want the below value column duplicated, using data from the next comment*/
verificationdata.Value

FROM event
INNER JOIN verification on event.Id = verification.EventId
INNER JOIN verificationdata on verificationdata.vId = verification.Id
WHERE event.Id > 00001
AND 
(verificationdata.Field = 'Grievances'OR verificationdata.Field = 'ERROR')

/*Pulling THIS data into the duplicated column*/
WHERE verificationdata.Field = 'VideoDurationPTS_0'



Id | Name | Date   | Size | Email     | verificationdata.Value  | verificationdata.Value                                   
01 | Dave | 01-Jan | 2000 | d@d.com   | A                       | B                            
02 | Bob  | 02-Jan | 3000 | b@b.com   | A                       | B

A =(validationdata.Field =申诉时的值) B =(verifydata.Field =持续时间时的值) 任何帮助都将是超级!

2 个答案:

答案 0 :(得分:1)

请尝试使用条件聚合

SELECT 
event.Id, 
event.Name, 
event.Date,
event.Size,  
event.Email,  
MAX(CASE WHEN verification.Field IN ('Grievances') THEN 'A' END) as val1,
MAX(CASE WHEN verification.Field IN ('VideoDurationPTS_0') THEN 'B' END) as 
val2
FROM event
INNER JOIN verification on event.Id = verification.EventId
INNER JOIN verificationdata on verificationdata.vId = verification.Id
WHERE event.Id > 00001
AND 
(verificationdata.Field in( 'Grievances','ERROR','VideoDurationPTS_0')
group by event.Id, event.Name, event.Date, event.Size,  event.Email

答案 1 :(得分:0)

如果我理解正确,那么您想要:

SELECT e.Id, e.Name, e.Date, e.Size, e.Email,  
       MAX(CASE WHEN vd.Field IN ('Grievances', 'ERROR') THEN vd.Value END) as field,
       MAX(CASE WHEN vd.Field IN ('VideoDurationPTS_0') THEN vd.Value END) as VideoDurationPTS_0
FROM event e INNER JOIN
     verification v
     ON e.Id = v.EventId INNER JOIN
     verificationdata vd
     ON vd.vId = v.Id
WHERE e.Id > 00001 AND
      vd.Field IN ('Grievances', 'ERROR', 'VideoDurationPTS_0')
GROUP BY e.Id, e.Name, e.Date, e.Size, e.Email;