如何在没有空输出的情况下合并所有和按多项选择分组?

时间:2019-04-22 07:41:40

标签: mysql sql

按联合和分组选择时,我遇到问题,输出上没有空输出。可能是因为内部有一些带有详细数据的输入和一些数学运算。 我有1个具有主键的视图表,并且有2个与2个表相关的外键。

我已经尝试通过合并所有代码并在内部分组依据来尝试此代码。

SELECT no_daftar,nama,(k1/jk1) as k1,(k2/jk2) as k2,(k3/jk3) as k3,(k4/jk4) as k4  FROM
(
SELECT no_daftar, nama,  SUM(k1) as k1,  SUM(k2)  as k2, SUM(k3) as k3, SUM(k4) as k4,
(SELECT COUNT(kode_aspek) FROM kriteria WHERE kode_aspek="K1" AND kode_aspek=a.kode_aspek) as jk1,
(SELECT COUNT(kode_aspek) FROM kriteria WHERE kode_aspek="K2" AND kode_aspek=a.kode_aspek) as jk2,
(SELECT COUNT(kode_aspek) FROM kriteria WHERE kode_aspek="K3" AND kode_aspek=a.kode_aspek) as jk3,
(SELECT COUNT(kode_aspek) FROM kriteria WHERE kode_aspek="K4" AND kode_aspek=a.kode_aspek) as jk4
    FROM 
(
SELECT no_daftar, nama, kode_aspek, nilai AS k1, 0 AS k2, 0 as k3, 0 as k4 FROM bobot WHERE kode_aspek =  'K1' AND tahun = 2019
UNION ALL
SELECT no_daftar, nama, kode_aspek, 0 AS k1, nilai AS k2, 0 as k3, 0 as k4 FROM bobot WHERE kode_aspek =  'K2' AND tahun = 2019
UNION ALL
SELECT no_daftar, nama, kode_aspek, 0 AS k1, 0 AS k2, nilai as k3, 0 as k4 FROM bobot WHERE kode_aspek =  'K3' AND tahun = 2019
UNION ALL
SELECT no_daftar, nama, kode_aspek, 0 AS k1, 0 AS k2, 0 as k3, nilai as k4 FROM bobot WHERE kode_aspek =  'K4' AND tahun = 2019
) AS a
LEFT JOIN aspek b ON ( a.kode_aspek = b.kode_aspek )
GROUP BY a.no_daftar, a.kode_aspek
) as SEMI

此处用于下载数据库的链接: https://drive.google.com/file/d/1a5BNT34v3keKwFaPxV73C48NzKQho34O/view?usp=sharing

我希望输出将是每1个主键,每行有4个输出,但实际结果是4行,且具有空表达式

1 个答案:

答案 0 :(得分:0)

不确定是否会得到您期望的结果。但是,除了使用UNION之外,您还可以尝试使用条件聚合来旋转K。

例如,这个未经测试的记事本涂鸦。

SELECT 
 bb.no_daftar, 
 bb.nama, 
 SUM(CASE WHEN bb.kode_aspek = 'K1' THEN bb.total_nilai/kr.cnt ELSE 0 END) AS k1,
 SUM(CASE WHEN bb.kode_aspek = 'K2' THEN bb.total_nilai/kr.cnt ELSE 0 END) AS k2,
 SUM(CASE WHEN bb.kode_aspek = 'K3' THEN bb.total_nilai/kr.cnt ELSE 0 END) AS k3,
 SUM(CASE WHEN bb.kode_aspek = 'K4' THEN bb.total_nilai/kr.cnt ELSE 0 END) AS k4
FROM
(
SELECT 
     no_daftar, kode_aspek,
     MAX(nama) AS nama,
     SUM(nilai) AS total_nilai
    FROM bobot
    WHERE tahun = 2019
      AND kode_aspek IN ('K1','K2','K3','K4')
    GROUP BY no_daftar, kode_aspek
) bb
LEFT JOIN
(
    SELECT kode_aspek, COUNT(*) AS cnt
    FROM kriteria
    WHERE kode_aspek IN('K1','K2','K3','K4')
    GROUP BY kode_aspek
) kr ON kr.kode_aspek = bb.kode_aspek
GROUP BY bb.no_daftar, bb.nama