如何编写COUNT(DISTINCT())查询?

时间:2015-10-03 14:38:22

标签: mysql sql postgresql sqlite

请帮我解决这个问题。

我有一个表学生,看起来像:

$scope.loginFacebook = function() { 

    Parse.FacebookUtils.logIn("email", { 

       success: function(user) {
          if (!user.existed()) { 
             FB.api('/me?fields=name,email', function (response) { 
                 var user = new Parse.User(); 
                 user.set("username", response.username); 
                 user.set("email", response.email);
             }); 

          } else {
             alert("You're logged in with Facebook!")
             //redirect to dashboard page
          }
        },
         error: function(user, error) {
          alert("User cancelled the Facebook login or did not fully authorize.");
        }
     });      
}; 

并希望得到所有参加课程的课程,例如:

*id, name, surname, year, course*
1, John, Johnson, 3, Economy
2, Lara, Croft, 2, Biology
3, Mark, Jones, 3, Economy
4, Jim, Smith, 1, IT
5, Sarah, Kennedy, 1, IT
6, Matt, Damon, 3, Economy

1 个答案:

答案 0 :(得分:2)

您不会使用count(distinct ...),只需在课程上分组并使用count()

select
  cource,
  count(*)
from
  Students
group by
  cource
order by
  cource

如果要在组内进行不同的计数,使用count(distinct ...)非常有用,例如计算year的不同值(在所有记录的隐式组中):

select
  count(distinct year)
from
  Students

这会为您提供结果3,因为有三个不同的值123

相关问题