简体   繁体   English

从Sql表计数不同的值

[英]Counting Distinct values from Sql Table

Following is a view of my table... 以下是我桌子的视图...

在此处输入图片说明

I am getting a hard time in getting desired result from a query. 我很难从查询中获得想要的结果。

My requirement looks like below image 我的要求如下图所示

在此处输入图片说明

It should be conditioned as follows -- 1)Within start date and end date. 它应满足以下条件:1)在开始日期和结束日期之内。

2)No as Pending . 2)没有待定。

3)Yes as Completed. 3)是的。

4)No+Yes as Total. 4)否+是总计。

5)Based On only one survey Type. 5)仅基于一种调查类型。

This is what i have tried and got result for above mentioned 1 to 4 condition , but how to impliment 5 condition ? 这是我为上面提到的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

Can anybody help me out in it. 有人可以帮我吗?

thanks in advance//// 提前致谢////

You would add a where clause into the subquery: 您可以在子查询中添加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;

By the way, the select distinct are redundant. 顺便说一句, select distinct是多余的。 You do not need them for this query. 您不需要此查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM