将选择查询与数据透视查询联接在一起

时间:2019-01-14 18:26:15

标签: mysql pivot

在选择查询和数据透视查询之间创建内部联接时,我一直没有成功。我在连接附近收到无法解决的语法错误。我正在使用MySQL,而且是嵌套查询的新手。

Tbl_1 
ID  FirstName   LastName    Company
123 Dave        Jones       Ajax Inc
567 Mike        Smith       Beta Corp
891 Jane        Allan       Allan Consulting

Tbl_2
ID  fname   ftext
123 Email   dave.jones@ajax.com
567 Email   mike.smith@beta.com
567 Phone   6469612351
891 Email   jane.allan@gmail.com
891 Phone   4086089414
891 Cell    4086852918

Tbl_1 Select Query

SELECT firstname, lastname, company, id 
FROM   Tbl_1 
ORDER BY lastname, firstname 

Table 2 Pivot Query

SELECT id, 
   Max(IF(fname = 'Email', ftext, NULL)) AS 'Work Email', 
   Max(IF(fname = 'Phone', ftext, NULL)) AS 'Work Phone', 
   Max(IF(fname = 'Cell', ftext, NULL))  AS 'Cell Phone' 
FROM   Tbl_2 
GROUP  BY id; 

[Desired Output][1]

3 个答案:

答案 0 :(得分:0)

您需要加入表并按所有没有聚合功能(例如MAX,SUM,...)的字段进行分组。

SELECT Tbl_1.FirstName
    ,Tbl_1.LastName
    ,Tbl_1.Company
    ,Tbl_1.ID
    ,MAX(IF(Tbl_2.fname = 'Email', Tbl_2.ftext, NULL)) AS 'Work Email'
    ,MAX(IF(Tbl_2.fname = 'Phone', Tbl_2.ftext, NULL)) AS 'Work Phone' 
    ,MAX(IF(Tbl_2.fname = 'Cell', Tbl_2.ftext, NULL))  AS 'Cell Phone' 
FROM Tbl_1
INNER JOIN Tbl_2 on Tbl_1.ID = Tbl_1.ID

GROUP BY
    Tbl_1.FirstName
    ,Tbl_1.LastName
    ,Tbl_1.Company
    ,Tbl_1.ID

答案 1 :(得分:0)

对不起,戴夫,但我没有得到您想要的输出,但是如果我不得不猜测,您可能想尝试将上述两个查询都作为子查询,然后左键联接:

SELECT * FROM
(SELECT firstname, lastname, company, id 
FROM  Tbl_1 
ORDER BY lastname, firstname) t1 LEFT JOIN
(SELECT id, 
   MAX(IF(fname = 'Email', ftext, NULL)) AS 'Work Email', 
   MAX(IF(fname = 'Phone', ftext, NULL)) AS 'Work Phone', 
   MAX(IF(fname = 'Cell', ftext, NULL))  AS 'Cell Phone' 
FROM Tbl_2 
GROUP BY id) t2 ON t1.id=t2.id;

答案 2 :(得分:0)

感谢您指出正确的方向。以下是我实际使用的抽象。

SELECT     tbl_1.id,
           tbl_1.firstname,
           tbl_1.lastname,
           tbl_1.company,
           max(IF(tbl_2.fname = 'Email', tbl_2.ftext, NULL)) AS 'Work Email',
           max(IF(tbl_2.fname = 'Phone', tbl_2.ftext, NULL)) AS 'Work Phone',
           max(IF(tbl_2.fname = 'Cell', tbl_2.ftext, NULL))  AS 'Cell Phone',
FROM       tbl_1
INNER JOIN tbl_2
ON         tbl_1.id = tbl_2.id
GROUP BY   tbl_1.id,
           tbl_1.firstname,
           tbl_1.lastname,
           tbl_1.company;