gpt4 book ai didi

mysql - 计算 Sql 表中的不同值

转载 作者:行者123 更新时间:2023-11-30 01:24:50 24 4
gpt4 key购买 nike

以下是我的 table 的 View ...

enter image description here

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

我的要求如下图所示

enter image description here

其条件应如下--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

任何人都可以帮我吗?

提前致谢////

最佳答案

您可以在子查询中添加一个 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 unique 是多余的。此查询不需要它们。

关于mysql - 计算 Sql 表中的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18123941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com