Sql Query用于选择具有聚合函数的列值?

时间:2016-10-28 11:58:12

标签: sql sql-server tsql

表:( tblUser)

 ______________________________
|Column Name  |  Data Type     |
|------------------------------|
|     ID      |     bigint     |
|  UserName   | nvarchar(100)  |
|  Password   | nvarchar(100)  |
|   Email     | nvarchar(200)  |
|  UserType   |      bit       |
|_____________|________________|

这就是我的尝试:

CREATE Procedure spAutheticateUser
@UserName nvarchar(100),
@Password nvarchar(200)
as
Begin
  Declare @Count int
  Declare @Type bit

  Select @Count = COUNT(UserName), @Type = UserType from tblUsers
  where [UserName] = @UserName and [Password] = @Password

  If (@Count = 1 and @Type = 'True')
  Begin
      Select 1 as ReturnCode
  End
  Else If (@Count = 1 and @Type = 'False')
  Begin
      Select 2 as ReturnCode
  End
  Else
  Begin
      Select -1 as ReturnCode
  End
End

这是我在SQLServer上遇到的错误:

  

专栏' tblUsers.UserType'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

实际上我想在loginButton_click函数后面调用这个存储过程。我想验证用户信息,我还想检查用户所属的类型。根据UserType,我将重定向到特定页面。

请指导我如何实现功能。感谢。

4 个答案:

答案 0 :(得分:0)

更改您的选择语句如下:

Select @Count = COUNT(UserName), @Type = UserType from tblUsers
where [UserName] = @UserName and [Password] = @Password
GROUP By UserType 

您将使用聚合函数,因此您必须按保留列进行分组,您已选择

答案 1 :(得分:0)

尝试按UserType将组添加到主查询。你得到一个计数(@UserName)有什么特别的原因吗?如果删除count函数,则不需要Group By子句。

答案 2 :(得分:0)

您正在检查表中是否有多个用户名记录。如果有更多记录,则可以有不同的UserType。一旦有多个记录,您对UserType不感兴趣,只需选择最小或最大用户类型。

select @Count = COUNT(UserName), @Type = MIN(UserType) 
from tblUsers
where [UserName] = @UserName and [Password] = @Password

整件事:

select 
  case
    when count(*) = 1 and min(usertype) = 'True' then 1
    when count(*) = 1 and min(usertype) = 'False' then 2
    else -1
  end as returncode
from tblusers
where username = @UserName and password = @Password

答案 3 :(得分:0)

对您的问题不是一个严格的答案,但有些提示与您的功能密切相关:

DECLARE
    @pwd_1 NVARCHAR(100),
    @pwd_2 NVARCHAR(100)

SET @pwd_1 = 'asdf'
SET @pwd_2 = 'asdf   '

SELECT 'access granted'
WHERE @pwd_1 = @pwd_2


SET @pwd_1 = 'ASDF'
SET @pwd_2 = 'asdf'

SELECT 'access granted'
WHERE @pwd_1 = @pwd_2

enter image description here