我们如何在MySQL中解决这种情况

时间:2018-08-07 10:07:28

标签: mysql sql pivot sql-query-store

我有这张桌子:

const qrCodeScannerBtn = document.getElementById('Btn');
const qrCodeScannerText = document.getElementById('Text');
const qrCodePreview = document.getElementById('preview');

const scanner = new Instascan.Scanner({
  video: qrCodePreview,
  mirror: false
});
scanner.addListener('scan', content => {
  qrCodeScannerText.value = content;
  scanner.stop();
});
qrCodeScannerBtn.addEventListener('click', () => {
  if (scanner._scanner._active) {
    return scanner.stop();
  }
  Instascan.Camera.getCameras()
    .then(function(cameras) {
      if (cameras.length) {
        const camera = cameras[cameras.length - 1];
        scanner.start(camera);
        console.log(scanner);
      } else {
        alert('No cameras found.');
      }
    })
    .catch(function(e) {
      console.error(e);
    });
});

但是要求输出是这样的:

+----------+--------+-----+--------+--------+
| personId | Name   | Age | height | weight |
+----------+--------+-----+--------+--------+
| 1        | Aritra | 20  | 5.6    | 56     |
| 1        | Aritra | 30  | 5.6    | 76     |
+----------+--------+-----+--------+--------+

我尝试使用数据透视获取此功能,但遇到了问题。不论是否使用数据透视,我该如何做?

谢谢。

1 个答案:

答案 0 :(得分:0)

union all可能是最简单的方法:

select 'Height' as attributeName, personId,
       (case when age = 30 then height end) as newValue,
       (case when age = 20 then height end) as oldValue
from t 
union all
select 'Weight' as attributeName, personId,
       (case when age = 30 then weight end) as newValue,
       (case when age = 20 then weight end) as oldValue;