如何从SQL Server 2012进行计划表查询?

时间:2016-11-19 07:38:00

标签: c# sql sql-server visual-studio

我需要帮助从我的表中为员工制作一个计划表主要问题是行不是从每一列的第一行开始所以行保持继续,见下图:

Table

我们可以看到下一列在第一行为空,从最后一行继续。这是我的查询和表格关系,你可以在下面看到。

enter image description here

SELECT        (SELECT        PEGAWAI.NAMAPEGAWAI
                      WHERE        (JADWAL.HARIKERJA = 'Tuesday')) AS Selasa,
                         (SELECT        PEGAWAI.NAMAPEGAWAI
                           WHERE        (JADWAL.HARIKERJA = 'Wednesday')) AS Rabu,
                         (SELECT        PEGAWAI.NAMAPEGAWAI
                           WHERE        (JADWAL.HARIKERJA = 'Thursday')) AS Kamis,
                         (SELECT        PEGAWAI.NAMAPEGAWAI
                           WHERE        (JADWAL.HARIKERJA = 'Friday')) AS Jumat,
                         (SELECT        PEGAWAI.NAMAPEGAWAI
                           WHERE        (JADWAL.HARIKERJA = 'Sabtu')) AS Saturday,
                         (SELECT        PEGAWAI.NAMAPEGAWAI
                           WHERE        (JADWAL.HARIKERJA = 'Monday')) AS Minggu FROM            JADWAL INNER JOIN
                     JADWALPEGAWAI ON JADWAL.IDJADWAL = JADWALPEGAWAI.IDJADWAL INNER JOIN
                     PEGAWAI ON JADWALPEGAWAI.IDPEGAWAI = PEGAWAI.IDPEGAWAI WHERE        (JADWAL.SHIFT = 'I')

1 个答案:

答案 0 :(得分:0)

您的查询似乎没有按预期运行的原因是您的查询中没有GROUP BY子句,这意味着您为每个子句获取一行输出(在本例中) JadwalPegawai表的一行。

至少在GROUP BY Pegawai.NamaPegawai条款之后添加WHERE …应解决此问题,但我认为我们可以做得更好:

Select Min(iif(j.Harikerja = 'Tuesday', p.NamaPegawai, Null)) As Selasa,
    Min(iif(j.Harikerja = 'Wednesday', p.NamaPegawai, Null)) As Rabu,
    …
  From Jadwal As j
  Join JadwalPegawai As jp On j.IdJadwal = jp.IdJadwal
  Join Pegawai As p On jp.IdPegawai = p.IdPegawai
  Where j.Shift = 'I'
  Group By p.NamaPegawai;

这应该在逻辑上等效,但不使用子查询。希望我没有拼写错误,我对印度尼西亚语不太好......