一个查询中的百分比

时间:2013-03-01 22:58:57

标签: sql tsql

我尝试将这两个查询组合起来产生一个百分比值。

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, regdate)) AS rdate, 
       COUNT(*) as sum 
FROM TBL where regdate > '2013-02-21' 
GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, regdate)) 
ORDER BY rdate DESC 

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, slutdatum)) AS sdate, 
       COUNT(*) as sum 
FROM TBL 
WHERE slutdatum > '2013-02-21' 
GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, slutdatum))       
ORDER BY sdate DESC

但我真的不明白。我试过如下所示,但只产生错误,这两个查询由它自己运行; (我可以将查询分开运行并在获取值后进行数学运算,但只有接近它才会过度)。

SELECT (SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, regdate)) AS rdate, count(*) as sum 
        FROM TBL where regdate > '2013-02-21' 
        GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, regdate)) 
        ORDER BY rdate DESC) / (select DATEADD(dd, 0, DATEDIFF(dd, 0, slutdatum)) AS sdate,    
COUNT(*) as sum from TBL where slutdatum > '2013-02-21' 
GROUP BY DATEADD(dd, 0,    
DATEDIFF(dd, 0, slutdatum)) ORDER BY sdate DESC) * 100 from tbl

如何制作一个产生两个列的查询,过去7天的日期和百分比?

2 个答案:

答案 0 :(得分:1)

由于您将比较在同一天发生的事件,我们可以在日期加入,但我们需要FULL OUTER JOIN包括那里的日子只是休息或只是修复。

这是更新后的代码:

SELECT COALESCE(reg.rdate,cl.sdate) as [Date], ISNULL(reg.sum, 0) as [Registered], ISNULL(cl.sum, 0) as [Closed], 
       CASE WHEN cl.sum IS NULL THEN 0
            WHEN ISNULL(cl.sum,0) > ISNULL(reg.sum,0) THEN 100 
            ELSE CONVERT(float,cl.sum)/reg.sum*100 END as [Percentage]  
FROM 

(SELECT regdate AS rdate, COUNT(regdate) as sum 
FROM TBL where regdate > CONVERT(datetime,'20130221',112) 
GROUP BY regdate ) reg 

FULL OUTER JOIN 

(SELECT slutdatum AS sdate, COUNT(slutdatum) as sum 
FROM TBL WHERE slutdatum > CONVERT(datetime,'20130221',112)
GROUP BY slutdatum) cl

ON (reg.rdate=cl.sdate)
ORDER BY COALESCE(reg.rdate,cl.sdate);

我使用测试数据创建了SQL Fiddle,因此您可以尝试使用代码:http://sqlfiddle.com/#!3/58a33/1

答案 1 :(得分:0)

您可以像桌子一样使用(SELECT ...)。因此,尝试SELECT ... FROM(SELECT ...)作为A,(SELECT ...)作为B

现在,您可以在同一公式中使用A和B中的值。