GROUP BY / Aggregate函数说明

时间:2014-01-08 00:30:17

标签: asp.net sql gridview

我的每个Gridview元素都有一个SQL查询。一个是通过分支和交易日期获得所有交易:

SELECT 
            tb_TransactionDetails.TxnID,
            tb_TransactionDetails.BranchCode, 
            tb_TransactionDetails.TxnDate, 
            tb_TransactionDetails.ReferenceNo,
            tb_TransactionType.TxnTypeName,
            tb_CurrencyCode.CCYDesc,
            tb_TransactionDetails.CCYAmount,
            tb_RecordStatus.StatusDesc,
            (tb_TransactionName.FirstName + ' ' + ISNULL(tb_TransactionName.MiddleName,'') + ' ' + ISNULL(tb_TransactionName.LastName,'')) as 'Client',
            (tb_TransactionName.AddressLine1  + ' ' + ISNULL(tb_TransactionName.AddressLine2, '') + ' ' + ISNULL(tb_TransactionName.AddressLine3, '')) as 'Address',
            tb_TransactionName.WhoAdded,
            tb_TransactionName.DateAdded,
            ROW_NUMBER() OVER 
            (ORDER BY BranchCode ) AS RowNumber
            FROM (((tb_TransactionType inner join tb_TransactionDetails 
                on tb_TransactionType.TxnTypeCode = tb_TransactionDetails.TxnType)
                INNER JOIN tb_CurrencyCode on tb_TransactionDetails.CCYCode = tb_CurrencyCode.CCYCode)
                inner join tb_RecordStatus on tb_TransactionDetails.RecordStatus = tb_RecordStatus.StatusCode)
                LEFT JOIN tb_TransactionName
            on tb_TransactionDetails.TxnID = tb_TransactionName.TxnID
            WHERE BranchCode = '1003' 
            and TxnDate = '12/13/2013'

一个是获得系统中的所有用户:

    select
    USR.UserName,
    USR.BranchID,
    (ISNULL(USR.FirstName,'') + ' ' + ISNULL((SUBSTRING(USR.MiddleName,1,1) + '.' ),'') + ' ' + ISNULL(USR.LastName,'')) as 'Name',
    MBS.IsLockedOut,
    USR.LastActivityDate,
    MAX(STUFF(fxMerge.RoleId, 1, 2, '')) as 'Roles'
    from (aspnet_Membership as MBS inner join aspnet_Users as USR
    on USR.ApplicationId = USR.ApplicationId and MBS.UserId = USR.UserId)
    inner join aspnet_UsersInRoles UIR
    on USR.UserId = UIR.UserId

    CROSS APPLY(
    SELECT ', ' + RoleName 
    FROM aspnet_UsersInRoles UIR1
    INNER JOIN aspnet_Roles RM ON UIR1.RoleId = RM.RoleID
    WHERE UIR.UserId = UIR1.UserId
    FOR XML PATH('')) fxMerge (RoleId)

where USR.UserName = 'JSmith'

group by USR.UserName, USR.BranchID, USR.FirstName, USR.MiddleName, USR.LastName, MBS.IsLockedOut, USR.LastActivityDate

我很困惑的一件事是,第一个查询不需要GROUP BY子句,而第二个查询不需要GROUP BY子句。我的问题是,为什么?我一直在运行第一个查询数百次在我的系统中没有问题,而不需要GROUP BY子句,Gridview显示预期的结果。在我的第二个查询中,只有当我在SQL Server Management工作室上添加查询成功执行的长Gridview子句时,才会在{{1}}上显示任何内容。

1 个答案:

答案 0 :(得分:0)

那是因为你的第二个查询有一个MAX()。如果您想要最高或最低值,或计数或任何其他聚合函数,您需要指定如何对其进行分组。