选择中有多个案例

时间:2014-12-15 19:12:49

标签: mysql sql-server select case temporary

我有一个问题,我必须将以下MSSQL转换为MySQL。我有两个主要问题。

  1. "#WU"是一个不起作用的临时表。我试着替换它 CREATE TEMPORARY TABLE WU但是没有解释就错了。
  2. 我想知道调用多个案例的正确方法。
  3. 我已尝试移除MAX,并将其切换为WU1 =(例如,当rk = 1那么结束时),但这不起作用。

    代码如下:

    SELECT ReqN,
    MAX(CASE WHEN rk = 1 THEN WU END) AS WU1,
    MAX(CASE WHEN rk = 2 THEN WU END) AS WU2,
    MAX(CASE WHEN rk = 3 THEN WU END) AS WU3,
    MAX(CASE WHEN rk = 4 THEN WU END) AS WU4,
    MAX(CASE WHEN rk = 5 THEN WU END) AS WU5,
    MAX(CASE WHEN rk = 6 THEN WU END) AS WU6,
    MAX(CASE WHEN rk = 7 THEN WU END) AS WU7,
    MAX(CASE WHEN rk = 8 THEN WU END) AS WU8
    
    into #tblWU
    
    FROM (SELECT ReqN, WUnit,
       (SELECT COUNT(*) 
        FROM tblDevWU AS B
        WHERE B.ReqN = A.ReqN
        AND B.WUnit <= A.WUnit) AS rk
        FROM tblDevWU AS A) as A 
        GROUP BY ReqN;
    

1 个答案:

答案 0 :(得分:1)

与此等效的Mysql是:

CREATE TEMPORARY TABLE tblWU AS
SELECT ReqN,
MAX(IF(rk=1, WU, NULL)) WU1,
MAX(IF(rk=2, WU, NULL)) WU2,
MAX(IF(rk=3, WU, NULL)) WU3,
MAX(IF(rk=4, WU, NULL)) WU4,
MAX(IF(rk=5, WU, NULL)) WU5,
MAX(IF(rk=6, WU, NULL)) WU6,
MAX(IF(rk=7, WU, NULL)) WU7,
MAX(IF(rk=8, WU, NULL)) WU8
FROM (
   SELECT ReqN, WUnit,
      (
       SELECT COUNT(*) FROM tblDevWU AS B
       WHERE B.ReqN = A.ReqN AND B.WUnit <= A.WUnit
      ) AS rk
   FROM tblDevWU AS A) as A 
GROUP BY ReqN;