别名行的动态查询

时间:2012-10-19 17:24:11

标签: sql

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而不是任何帮助?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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