以下是我的表格的视图......
我很难从查询中获得所需的结果。
我的要求如下图所示
它的条件如下 - 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
任何人都可以帮助我。
提前谢谢////
答案 0 :(得分: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
是多余的。此查询不需要它们。