Sql - 两个temptables /子查询之间的计算

时间:2018-03-22 19:06:11

标签: sql

我对SQL没有最好的理解,尽力学习。我已经构建了两个单独的查询,我希望从查询1中获取结果并将其除以查询2.我使用了union语句和我的两个查询。

select 
    * 
from
    (select count(*) as Numerator
     from 
         (select
              *,  
              datediff(second, yy, xx) as SecondDiff, 
              datediff(day, yy, xx) as DayDiff
          from
              database1.dbo.table1
          where
              month(datecompleted) = month(dateadd(month, -1, current_timestamp))
              and year(datecompleted) = year(dateadd(month, -1, current_timestamp))
              and datediff(day, yy,xx) <= 15) temptable

     union 

     select count(*) as Denominator
     from
         (select
              *,  
              datediff(second, yy, xx) as SecondDiff, 
              datediff(day, yy, xx) as DayDiff
          from
              database2.dbo.table2
          where  
              month(datecompleted) = month(dateadd(month, -1, current_timestamp))
              and year(datecompleted) = year(dateadd(month, -1, current_timestamp))) temptable1
    ) finaltable

执行此查询时,我得到以下结果;

Numerator
-----------    
114
131

我想将114除以131并显示一个名为“x”的新列作为结果。

非常感谢所有提示和建议。

谢谢

2 个答案:

答案 0 :(得分:0)

尝试以下方法;

SELECT *
    ,Numerator / Denominator AS x
FROM (
    SELECT count(*) AS Numerator
    FROM (
        SELECT *
            ,DATEDIFF(SECOND, yy, xx) AS SecondDiff
            ,DATEDIFF(DAY, yy, xx) AS DayDiff
        FROM database1.dbo.table1
        WHERE month(datecompleted) = month(dateadd(month, - 1, current_timestamp))
            AND year(datecompleted) = year(dateadd(month, - 1, current_timestamp))
            AND DATEDIFF(DAY, yy, xx) <= 15
        ) t
    CROSS APPLY (
        SELECT count(*) AS Denominator
        FROM (
            SELECT *
                ,DATEDIFF(SECOND, yy, xx) AS SecondDiff
                ,DATEDIFF(DAY, yy, xx) AS DayDiff
            FROM database2.dbo.table2
            WHERE month(datecompleted) = month(dateadd(month, - 1, current_timestamp))
                AND year(datecompleted) = year(dateadd(month, - 1, current_timestamp))
            )
        ) AS t1
    WHERE 1 = 1
    ) AS Tbl

答案 1 :(得分:0)

尝试CTE如下:

;with t1 as (
select count(*) as Numerator
from (

SELECT *,  DATEDIFF(SECOND, yy, xx) AS SecondDiff, 
           DATEDIFF(DAY, yy, xx) AS DayDiff

FROM database1.dbo.table1

WHERE  month(datecompleted) = month(dateadd(month,-1,current_timestamp))
       and year(datecompleted) = year(dateadd(month,-1,current_timestamp))
       and DATEDIFF(DAY, yy,xx) <= 15

)temptable),

t2 as(

select count(*) as Denominator

from(

SELECT *,  DATEDIFF(SECOND, yy, xx) AS SecondDiff, 
           DATEDIFF(DAY, yy, xx) AS DayDiff

FROM database2.dbo.table2

WHERE  month(datecompleted) = month(dateadd(month,-1,current_timestamp))
       and year(datecompleted) = year(dateadd(month,-1,current_timestamp))

)temptable1)

从t1,t2选择t1.Numerator / t2.Denominator为DivResult