开发者

Mysql add second query to the same request, its complicated

开发者 https://www.devze.com 2023-04-10 03:45 出处:网络
I have this kind of request: SELECT employers.employer_name, p.position_name, SUM(CASE WHEN w.type = 2 THEN 1 ELSE 0 END) AS booked,

I have this

kind of request:
    SELECT employers.employer_name, p.position_name,
         SUM(CASE WHEN w.type = 2 THEN 1 ELSE 0 END) AS booked,
         SUM(CASE WHEN (w.type = 3 OR w.type = 31) THEN 1 ELSE 0 END) AS placed
        FROM places AS p
              LEFT JOIN employers ON employers.id = places.employer
          LEFT JOIN (
         开发者_开发技巧   SELECT
              w.id,
              w.user_id,
              CASE x.pos WHEN 1 THEN w.pos1 ELSE w.pos2 END AS position,
              CASE w.type
                WHEN 39 THEN CASE x.pos WHEN 1 THEN 3 ELSE 2 END
                ELSE w.type
              END AS type
            FROM workers AS w
              CROSS JOIN (SELECT 1 AS pos UNION ALL SELECT 2) AS x
          ) AS w
          ON w.position = p.pos_id
        GROUP BY p.pos_id, p.pos_name
        ORDER BY p.emp_id ASC, p.pos_id ASC

i need to modify it to add selection of places.position_name when workers.position2 = places.position_id how can i do it?


I'm a little unclear as to whether places.position_id is the same column as places.pos_id and whether workers.position2 is the same as workers.pos2. Anyway, I've assumed that they are not equal i.e. exactly as described in the question.

Give this a go - it might need some column tweaking depending on position_name vs pos_name and pos2 vs position2:

SELECT employers.employer_name, p.position_name,
     case when w.position2 = p.position_id then p.position_name else 'no worker position found' end as worker_position_name,
     SUM(CASE WHEN w.type = 2 THEN 1 ELSE 0 END) AS booked,
     SUM(CASE WHEN (w.type = 3 OR w.type = 31) THEN 1 ELSE 0 END) AS placed
    FROM places AS p
          LEFT JOIN employers ON employers.id = places.employer
      LEFT JOIN (
        SELECT
          w.id,
          w.user_id,
          CASE x.pos WHEN 1 THEN w.pos1 ELSE w.pos2 END AS position,
          CASE w.type
            WHEN 39 THEN CASE x.pos WHEN 1 THEN 3 ELSE 2 END
            ELSE w.type
          END AS type,
          w.pos2
        FROM workers AS w
          CROSS JOIN (SELECT 1 AS pos UNION ALL SELECT 2) AS x
      ) AS w
      ON w.position = p.pos_id
    GROUP BY p.pos_id, p.pos_name,w.position2,p.position_id,p.position_name
    ORDER BY p.emp_id ASC, p.pos_id ASC;  

Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号