2
SELECT
--DISTINCT
organizations.Name,users.FName, users.LName, UserTypes.Name, users.Email, Users.id,
(SELECT COUNT(MessageId)) As MsgsReceived,
(SELECT COUNT(MessageID)
WHERE Messages.Urgency = 1) AS LowMsgsReceived,
(SELECT COUNT(MessageID)
WHERE Messages.Urgency = 2) AS MedMsgsReceived,
(SELECT COUNT(MessageID)
WHERE Messages.Urgency = 3) AS HighMsgsReceived
FROM Users
INNER JOIN Recipients ON
Users.ID = Recipients.UserId
INNER JOIN Messages ON
Messages.ID = Recipients.MessageID
INNER JOIN UserTypes ON
Users.UserTypeID = UserTypes.ID
INNER JOIN Organizations ON
Users.OrganizationId = Organizations.Id
GROUP BY organizations.Name,users.FName, users.LName, UserTypes.Name, users.Email, Users.id, Messages.Urgency
ORDER BY Users.FName

计数给了我收到的消息级别的错误结果。下面的查询给了我正确的计数,但有些行我不想在上面显示 null,而是显示 0,有什么帮助吗?

4

2 回答 2

0

你也可以试试这个:

SELECT      --DISTINCT
            organizations.Name
            , users.FName
            , users.LName
            , UserTypes.Name
            , users.Email
            , Users.id
            , COUNT(MessageId) As MsgsReceived
            , SUM(CASE WHEN Messages.Urgency = 1 THEN 1 ELSE 0 END) AS LowMsgsReceived
            , SUM(CASE WHEN Messages.Urgency = 2 THEN 1 ELSE 0 END) AS MedMsgsReceived
            , SUM(CASE WHEN Messages.Urgency = 3 THEN 1 ELSE 0 END) AS HighMsgsReceived
FROM        Users
            INNER JOIN Recipients
                ON Users.ID = Recipients.UserId
            INNER JOIN Messages
                ON Messages.ID = Recipients.MessageID
            INNER JOIN UserTypes
                ON Users.UserTypeID = UserTypes.ID
            INNER JOIN Organizations
                ON Users.OrganizationId = Organizations.Id
GROUP BY    organizations.Name
            ,users.FName
            , users.LName
            , UserTypes.Name
            , users.Email
            , Users.id
            , Messages.Urgency
ORDER BY    Users.FName
于 2012-10-24T21:12:00.167 回答
0

尝试这个

     Select u.fname, u.lName, u.Id,
        Count(m.Id) messagesRecvd,
        Sum(Case m.Urgency When 1 Then 1 End) LowMsgsRecvd,
        Sum(Case m.Urgency When 2 Then 1 End) MedMsgsRecvd,
        Sum(Case m.Urgency When 3 Then 1 End) HighMsgsRecvd
     From users u
        Left Join (Messages m Join Recipients r
                       On r.MessageId = m.Id)
            On r.UserId = u.Id
     Group By u.fname, u.lName, u.Id
     Order by u.fName
于 2012-10-19T17:31:08.827 回答