在SELECT查询中提取数据

时间:2017-01-25 05:17:28

标签: mysql sql

是否可以通过从中提取数据来查询获取表的行?

这是我的表:

leave_count_id  leave_count     leave_user_id   leave_id        leave_earned
1               0.0             1               1               15.000
2               0.0             1               2               15.000
3               2.5             2               1               15.000
4               0.0             2               2               15.000
5               2.0             3               1               15.000
6               1.0             3               2               15.000
7               2.0             4               1               15.000
8               1.0             4               2               15.000

这就是我想要的:

leave_user_id   sickLeave   vacationLeave
1               0           0
2               0           2.5
3               1           2
4               1           2

我的sql代码是这样的:

SELECT leave_user_id, slCount, vlCount

FROM (
SELECT
(SELECT leave_count FROM tbl_leave_count lc WHERE leave_id = 1 and lc.leave_user_id = leave_user_id) as vlCount,
(SELECT leave_count FROM tbl_leave_count lc WHERE leave_id = 2 and lc.leave_user_id = leave_user_id) as slCount,
FROM
tbl_leave_count

WHERE lc.leave_user_id = leave_user_id
) T

但它有错误。我不知道该怎么办。有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:1)

假设每个用户有一个病假条目和一个休假条目,而没有其他条目,那么以下简单的透视查询应该有效:

SELECT leave_user_id,
      MAX(CASE WHEN leave_id = 2 THEN leave_count END) AS sickLeave,
      MAX(CASE WHEN leave_id = 1 THEN leave_count END) AS vacationLeave
FROM tbl_leave_count
GROUP BY leave_user_id

数据透视查询在分组记录时使用技巧。在上述查询的情况下计算病假时,对于每个leave_user_id组记录,它需要leave_count列的最大值。只有两个记录,因此有两个值。一个值是我们在结果集中需要的数字,另一个是NULLMAX()函数忽略了空值,因此我们只剩下我们想要的数据。

如果用户可以拥有多条病假和休假记录,那么您可以尝试这样做:

SELECT leave_user_id,
      SUM(CASE WHEN leave_id = 2 THEN leave_count ELSE 0 END) AS sickLeave,
      SUM(CASE WHEN leave_id = 1 THEN leave_count ELSE 0 END) AS vacationLeave
FROM tbl_leave_count
GROUP BY leave_user_id

答案 1 :(得分:0)

我猜你没有从嵌套select中的表中选择leave_user_id。希望这会有所帮助