0

以下是我的桌子的视图......

在此处输入图像描述

我很难从查询中获得所需的结果。

我的要求如下图所示

在此处输入图像描述

条件如下: 1)在开始日期和结束日期内。

2)没有待处理。

3) 是的,已完成。

4) 否+是总计。

5)仅基于一种调查类型。

这是我已经尝试并得到了上述 1 到 4 条件的结果,但是如何实现 5 条件?

SELECT DISTINCT Userid
  ,CASE 
    WHEN [YES] IS NULL
      THEN 0
    ELSE [YES]
    END AS Completed
  ,CASE 
    WHEN [NO] IS NULL
      THEN 0
    ELSE [NO]
    END AS Pending
  ,(
    CASE 
      WHEN [YES] IS NULL
        THEN 0
      ELSE [YES]
      END + CASE 
      WHEN [NO] IS NULL
        THEN 0
      ELSE [NO]
      END
    ) AS Total
FROM (SELECT DISTINCT Userid
    ,SurveyStatus
    ,COUNT(ParcelId) AS cnt
  FROM ParcelAllocationsurvivor
  WHERE DateAllocated >= '2013-08-01'
    AND DateAllocated <= '2013-08-07'
  GROUP BY Userid
    ,SurveyStatus
  ) AS p
PIVOT(max(cnt) FOR surveystatus IN ([YES],[NO])) AS pvt
ORDER BY Userid

任何人都可以帮助我。

提前致谢////

4

1 回答 1

0

您将where在子查询中添加一个子句:

SELECT Userid, (case when [YES] is null then 0 else [YES] end) as Completed,
       (case when [NO] is null then 0 else [NO] end) as Pending,
       (case when [YES] is null then 0 else [YES] end +
        case when [NO] is null then 0 else [NO] end
       ) as Total
FROM (SELECT Userid, SurveyStatus, COUNT(ParcelId) as cnt 
      FROM ParcelAllocationsurvivor
      WHERE DateAllocated >= '2013-08-01' and DateAllocated <='2013-08-07' and
            SurveyType = 'Survey1'
      group by Userid, SurveyStatus
     ) AS p
PIVOT(max(cnt) FOR surveystatus IN([YES],[NO])) AS pvt order by Userid;

顺便说一句,它们select distinct是多余的。此查询不需要它们。

于 2013-08-08T10:54:18.237 回答