我对SQL很新,我在Khan Academy上自学了SQL。我按如下方式创建了一个数据库表:
CREATE TABLE Data_Exp (ID INTEGER PRIMARY KEY AUTOINCREMENT, Subject TEXT,
Label TEXT, Gender TEXT, X1 INTEGER, X2 INTEGER,
X3 INTEGER, X4 INTEGER, X5 INTEGER);
INSERT INTO Data_Exp(Subject, Label, Gender, X1, X2, X3, X4, X5) VALUES("S01", "A", "F", 5, 7, 6, 5, 4);
INSERT INTO Data_Exp(Subject, Label, Gender, X1, X2, X3, X4, X5) VALUES("S02", "B", "M", 8, 8, 6, 4, 6);
INSERT INTO Data_Exp(Subject, Label, Gender, X1, X2, X3, X4, X5) VALUES("S03", "A", "M", 6, 1, 4, 3, 3);
INSERT INTO Data_Exp(Subject, Label, Gender, X1, X2, X3, X4, X5) VALUES("S04", "C", "F", 3, 3, 7, 2, 5);
INSERT INTO Data_Exp(Subject, Label, Gender, X1, X2, X3, X4, X5) VALUES("S05", "B", "F", 9, 2, 5, 3, 7);
上述代码的输出为:
然后我继续添加此代码:
SELECT Subject, Gender, Label, ROUND(0.4*X1 + 0.15*(X2+X3+X4+X5),1) AS Y FROM Data_Exp;
并获得以下结果(如预期的那样):
然后我使用CASE语句来评估列级别:
SELECT Subject, Gender, Label, (SELECT CASE WHEN Y > 6 THEN "Level 6"
WHEN Y > 5 THEN "Level 5"
WHEN Y > 4 THEN "Level 4"
WHEN Y > 3 THEN "Level 3"
WHEN Y > 2 THEN "Level 2"
WHEN Y > 1 THEN "Level 1"
END AS "Level" FROM (SELECT ROUND(0.4*X1 + 0.15*(X2+X3+X4+X5),1) AS Y FROM Data_Exp)) AS Level FROM Data_Exp;
但不是得到这个结果:
我在列级别
中得到了这个奇怪的输出我哪里出错?
答案 0 :(得分:1)
您的查询无效,因为您正在进行某种笛卡尔式加入
您正在寻找的是类似下面的解决方案
SELECT Subject,
Gender,
Label,
CASE WHEN ROUND(0.4*X1 + 0.15*(X2+X3+X4+X5),1) > 6 THEN "Level 6"
WHEN ROUND(0.4*X1 + 0.15*(X2+X3+X4+X5),1) > 5 THEN "Level 5"
WHEN ROUND(0.4*X1 + 0.15*(X2+X3+X4+X5),1) > 4 THEN "Level 4"
WHEN ROUND(0.4*X1 + 0.15*(X2+X3+X4+X5),1) > 3 THEN "Level 3"
WHEN ROUND(0.4*X1 + 0.15*(X2+X3+X4+X5),1) > 2 THEN "Level 2"
WHEN ROUND(0.4*X1 + 0.15*(X2+X3+X4+X5),1) > 1 THEN "Level 1"
END AS "Level"
FROM Data_Exp;
否则您可以使用下面的模板。
下面的查询需要修补,对于你想要实现的目标而言可能很乏味
SELECT Subject,
Gender,
Label,
(
SELECT CASE WHEN Y > 6 THEN "Level 6"
WHEN Y > 5 THEN "Level 5"
WHEN Y > 4 THEN "Level 4"
WHEN Y > 3 THEN "Level 3"
WHEN Y > 2 THEN "Level 2"
WHEN Y > 1 THEN "Level 1"
END AS "Level"
FROM
(SELECT ROUND(0.4*X1 + 0.15*(X2+X3+X4+X5),1) AS "Y" FROM Data_Exp) AS "lol"
INNER JOIN Data_Exp ON Data_Exp.Gender = lol.Gender AND Data_Exp.Label = lol.Label
) AS "Level"
FROM
FROM Data_Exp;
最后但并非最不重要的是,了解您的数据库(Postgres
,MySql
或其他内容)将有所帮助,因为您可以使用其他解决方案(如声明变量)来存储公式,这肯定更容易。< / p>