SQL:如何对别名计算列ADD添加计数?

时间:2014-10-10 12:53:31

标签: mysql sql

我是SQL的新手,很难从我的数据库中获取信息,也许有人可以提供指导。我有

表:学生

专栏:

name, notes, test_1_score, test_2_score, test_3_score, test_4_score, test_5_score,
test_6_score, test_7_score, test_8_score, test_9_score, test_10_score

我可以在没有GROUP BY中的points_achieved的情况下运行以下代码,但这就是我想要排序的内容。另外,如果没有添加IsNull,我无法进行计算。

SELECT
name, 
notes, 
SUM (IsNull (test_1_score, 0) + IsNull (test_2_score, 0) + IsNull (test_3_score, 0) + IsNull (test_4_score, 0) + IsNull (test_5_score, 0) +IsNull ( test_6_score, 0) + IsNull (test_7_score, 0) + IsNull (test_8_score, 0) + IsNull (test_9_score, 0) + IsNull (test_10_score, 0)) AS points_acheived
FROM students
GROUP BY
points_achieved, name, notes;

最终,我想要一个简单的答案来表明: name points_achieved(加上#tests完成的计数)...... .notes

非常感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT
name, 
notes, 
SUM (IsNull (test_1_score, 0) + IsNull (test_2_score, 0) + IsNull (test_3_score, 0) + IsNull (test_4_score, 0) + IsNull (test_5_score, 0) +IsNull ( test_6_score, 0) + IsNull (test_7_score, 0) + IsNull (test_8_score, 0) + IsNull (test_9_score, 0) + IsNull (test_10_score, 0)) AS points_acheived
FROM students
GROUP BY
points_achieved, name, notes
order by 3;

答案 1 :(得分:0)

您可以利用SQL中的各种布尔运算符的值为1或0表示true或false的事实。

因此,如果该列具有有效值,则表达式test_1_score IS NOT NULL将具有值1

使用此查询:

SELECT name, notes,
       SUM(IsNull(test_1_score,0) + /* etc */) AS points_achieved
       SUM((test_1_score IS NOT NULL) + (test_2_score IS NOT NULL) + /*etc*/) AS tests_taken
  FROM students
 GROUP BY name, notes