只是寻找我的问题的任何信息,不一定是确切的答案。
我有一张名为WorkDay的表。
在工作日表中,有6个字段:
Date_of_Workday, Workday_type, Boss, Regular, Tech1, Tech2.
可以为员工分配多个角色,还有一些字段为NULL。
我想写一个查询,它将返回分配给每个工作日的员工总数,但很明显,如果有员工分配给Boss角色以及Tech2角色,那么这只会算作一名员工。
编辑: 这是我想要的输出。
+------------+------------+----+
|Date_of_Work| Work_type | |
+------------+------------+----+
| 2019-02-09 | AM | 4 |
| 2019-02-09 | PM | 4 |
| 2019-02-10 | AM | 3 |
| 2019-02-10 | PM | 2 |
| 2019-02-11 | AM | 4 |
| 2019-02-11 | PM | 4 |
| 2019-02-12 | AM | 4 |
| 2019-02-12 | PM | 4 |
| 2019-02-13 | AM | 4 |
| 2019-02-13 | PM | 4 |
------------+------------+----
这是SELECT * FROM Workday:
+------------+------------+---------+----------+-----------+-----------+
| DateofWork | workday_typ | Boss | Regular | Tech1 | Tech2 |
+------------+------------+---------+----------+-----------+-----------+
| 2019-02-09 | AM | LB1 | AW1 | AE1 | JE1 |
| 2019-02-09 | PM | AE1 | IM1 | AL1 | BJ1 |
| 2019-02-10 | AM | AE1 | MM1 | MW1 | NULL |
| 2019-02-10 | PM | AE1 | AE1 | EB1 | NULL |
| 2019-02-11 | AM | LB1 | AB1 | DJ1 | JP1 |
| 2019-02-11 | PM | LB1 | JE1 | AB2 | BJ1 |
| 2019-02-12 | AM | LB1 | NS1 | AE1 | MB1 |
| 2019-02-12 | PM | LB1 | HP1 | EH1 | AL1 |
| 2019-02-13 | AM | LB1 | EB2 | ME1 | MM1 |
| 2019-02-13 | PM | LB1 | ME2 | AB2 | DJ1 |
+------------+------------+---------+----------+-----------+-----------+
我不确定是否要进行此查询。任何信息/指针将不胜感激。
答案 0 :(得分:1)
看起来你糟糕的非规范化表格中有多个包含人名的列。您希望计算每天所有这些列中唯一值的数量。
尝试这样的方法来获取每天的独特价值。这将返回一个以Date_of_Workday, Workday_Type, Person
为列的结果集。 UNION
的使用消除了重复的Person
值。
SELECT Date_of_Workday, Workday_Type, Boss AS Person FROM tbl
UNION
SELECT Date_of_Workday, Workday_Type, Regular AS Person FROM tbl
UNION
SELECT Date_of_Workday, Workday_Type, Tech1 AS Person FROM tbl
UNION
SELECT Date_of_Workday, Workday_Type, Tech2 AS Person FROM tbl
然后在聚合查询中使用该子查询,如下所示:(http://sqlfiddle.com/#!9/f1320a/1/0)
SELECT Date_of_Workday, Workday_Type, COUNT(Person) AS PersonCount
FROM (
SELECT Date_of_Workday, Workday_Type, Boss AS Person FROM tbl
UNION
SELECT Date_of_Workday, Workday_Type, Regular AS Person FROM tbl
UNION
SELECT Date_of_Workday, Workday_Type, Tech1 AS Person FROM tbl
UNION
SELECT Date_of_Workday, Workday_Type, Tech2 AS Person FROM tbl
) Persons
GROUP BY Date_of_Workday, Workday_Type
您需要COUNT(Person)
而不是COUNT(*)
,否则会计算NULL
个值,因此会超出人数。