mysql数据透视查询 - 不需要具有NULL值的行

时间:2014-04-17 08:55:37

标签: mysql

物理治疗终止计划...... 表......

DROP TABLE IF EXISTS tag;
CREATE TABLE tag(VDATUM DATE NOT NULL,
                 VZEIT VARCHAR(5) NOT NULL,
                 BZEIT VARCHAR(5) NOT NULL,
                 FLAG VARCHAR(4) NOT NULL,
                 BEMERKUNG VARCHAR(20) NOT NULL
) ENGINE = MYISAM;

一些数据......

INSERT INTO tag(VDATUM,VZEIT,BZEIT,FLAG,BEMERKUNG)
VALUES ('2014-04-14','07:00','07:15','GUHI','PAUSE'), 
       ('2014-04-14','07:15','07:30','GUHI','PAUSE'),
       ('2014-04-14','07:30','07:45','GUHI','PatientXYZ'),
       ('2014-04-14','07:45','08:00','GUHI','*** 1/7'),
       ('2014-04-14','07:00','07:15','GUNE','PAUSE'), 
       ('2014-04-14','07:15','07:30','GUNE','PAUSE');

查询...

SELECT t.VDATUM,t.VZEIT,t.BZEIT,
       CASE 
           WHEN t.FLAG='GUHI' THEN (SELECT x.BEMERKUNG FROM tag x WHERE x.FLAG='GUHI' AND x.VDATUM=t.VDATUM AND x.VZEIT=t.VZEIT)
       END AS GUHI,
       CASE 
           WHEN t.FLAG='GUNE' THEN (SELECT x.BEMERKUNG FROM tag x WHERE x.FLAG='GUNE' AND x.VDATUM=t.VDATUM AND x.VZEIT=t.VZEIT)
       END AS GUNE
FROM tag t
WHERE t.VDATUM='2014-04-14';

结果......(错误)

  VDATUM    VZEIT   BZEIT   GUHI        GUNE
2014-04-14  07:00   07:15   PAUSE       NULL
2014-04-14  07:15   07:30   PAUSE       NULL
2014-04-14  07:30   07:45   PatientXYZ  NULL
2014-04-14  07:45   08:00   *** 1/7     NULL
2014-04-14  07:00   07:15   NULL        PAUSE
2014-04-14  07:15   07:30   NULL        PAUSE

应该如此......

  VDATUM    VZEIT   BZEIT   GUHI        GUNE
2014-04-14  07:00   07:15   PAUSE       PAUSE
2014-04-14  07:15   07:30   PAUSE       PAUSE
2014-04-14  07:30   07:45   PatientXYZ  
2014-04-14  07:45   08:00   *** 1/7 

我不需要具有NULL值的行... THX ...

1 个答案:

答案 0 :(得分:0)

SELECT 
t.VDATUM,
t.VZEIT,
t.BZEIT,
 (SELECT x.BEMERKUNG
    FROM tag x
   WHERE x.FLAG='GUHI' AND x.VDATUM=t.VDATUM AND x.VZEIT=t.VZEIT) AS GUHI,
 (SELECT x.BEMERKUNG
    FROM tag x
   WHERE x.FLAG='GUNE' AND x.VDATUM=t.VDATUM AND x.VZEIT=t.VZEIT) AS GUNE
FROM tag t
WHERE t.VDATUM='2014-04-14'
GROUP BY t.VDATUM, t.VZEIT, t.BZEIT