使用其他逻辑简化SQL查询

时间:2017-08-10 04:05:00

标签: sql

我正在尝试简化此查询:

        SELECT
        s.SurveyDate,
        S.Description,
        S.BadgeNum,
        S.UseriD,
       S.[LastName],
       S.[FirstName],
       SUM(S.NumberFCR) AS NumberResolved,
       SUM(S.NumberCases)AS NumberCases,
       CASE WHEN SUM(s.NumberCases) = 0 THEN 0
       ELSE cast(sum(S.NumberFCR) as DECIMAL)/cast(sum(S.NumberCases) AS Decimal) END AS FCR
FROM
(select 
        SurveyDate,
        Description,
        BadgeNum,
       COUNT(CaseNumber) NumberFCR,
       0 AS NumberCases,
       UserID,
       LastName,
       FirstName

from 
       [dbo].[SurveyData]
      INNER JOIN LOOKUP_REP on surveydata.UserId = lookup_rep.VoogleID
where 
       QuestionId = '3'  AND Answer = 'Yes'
        AND DATEPART(YYYY,SurveyDate) = DATEPART(yyyy,getdate())
        AND Description LIKE 'DD%'
GROUP BY
       Description,
       BadgeNum,
       UserID,
       Answer,
       LastName,
       FirstName,
       SurveyDate
UNION
select 
        SurveyDate,
        Description,
        BadgeNum,
       0 AS NumberFCR,
       COUNT(CaseNumber) AS NumberCases,
       UserID,
       LastName,
       FirstName
    from 
       [dbo].[SurveyData]
       INNER JOIN LOOKUP_REP on surveydata.UserId = lookup_rep.VoogleID
    where 
       QuestionId = '3'
    AND DATEPART(YYYY,SurveyDate) = DATEPART(yyyy,getdate())
    AND Description LIKE 'DD%'
    GROUP BY
       Description,
       UserID,
       Answer,
       LastName,
       BadgeNum,
       FirstName,
       SurveyDate
                        ) S 
     WHERE S.UseriD='vsd-1293'
     GROUP BY 
      S.[LastName],
       S.[FirstName],
       s.SurveyDate,
       Description,
       S.BadgeNum,
        S.UseriD

1 个答案:

答案 0 :(得分:0)

尝试以下查询,(使用过滤器答案='是'以防万一)

 SELECT
    s.SurveyDate,
    S.Description,
    S.BadgeNum,
    S.UseriD,
   S.[LastName],
   S.[FirstName],
   SUM(case when Answer = 'Yes'  then CaseNumber Else 0 End) AS NumberResolved,
   SUM(CaseNumber)AS NumberCases,
   CASE WHEN SUM(CaseNumber) = 0 THEN 0
   ELSE sum(case when Answer = 'Yes'  then CaseNumber Else 0 End)/sum(CaseNumber)*1.0 END AS FCR
FROM   [dbo].[SurveyData]
   INNER JOIN LOOKUP_REP on surveydata.UserId = lookup_rep.VoogleID
where 
QuestionId = '3'
AND DATEPART(YYYY,SurveyDate) = DATEPART(yyyy,getdate())
AND Description LIKE 'DD%'
and UseriD='vsd-1293'
GROUP BY
   Description,
   UserID,
   LastName,
   BadgeNum,
   FirstName,
   SurveyDate