我正在创建一个查询,其中我会计算申请人有多少奖励。到目前为止,我有这个:
SELECT
CASE WHEN Award1 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Award2 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Award3 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Award4 IS NOT NULL THEN 1 ELSE 0 END
as summedColumn
FROM resume, person
where E_Status = 'Applicant'
and person.ID_No like 'x' and resume.ID_No like 'x'
Table:Person Values
ID_No(Varchar, Primary) x
F_Name(Varchar) Fasa
L_Name(Varchar) Bel
M_Name(Varchar) Drake
Resume_ID(Varchar) res01
Table: Resume Value
Resume_ID(Varchar, Primary) res01
ID_No(Varchar) x
Award1(Varchar) Suma Cum Laude
Award2(Varchar) null
Award3(Varchar) null
Award4(Varchar) null
Past_Position1(Varchar) HR manager
Past_Position2(Varchar) null
Output of the query: 4
当我运行代码时,它返回值为4,但我的Award2,Award3和Award4都是null。代码假设返回值为1.
以下是表格的外观:
答案 0 :(得分:2)
你没有加入你的两个表,所以它在Resume和Person表之间进行交叉连接。
找到将Person与Resume相关联的键,并将它们放在一起:
SELECT
CASE WHEN Award1 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Award2 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Award3 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Award4 IS NOT NULL THEN 1 ELSE 0 END
as summedColumn
FROM resume
INNER JOIN person
ON resume.Resume_ID = person.Resume_ID
where E_Status = 'Applicant'
and person.ID_No like 'x' and resume.ID_No like 'x'
答案 1 :(得分:0)
也许您想重新考虑数据库结构。 如何创建1:n结构?
表格结构人:ID, Name ...
表格结构奖励:PersonID, AwardRel
表格结构奖励:ID, AwardName, ...
使用这样的1:n结构,您的查询可以表示为:
SELECT COUNT(*) FROM `AwardRel` WHERE `PersonID` = 1;
此查询应返回任何人1获得的任意数量的奖励。