如何编写SQL查询以选择内部连接的百分比?

时间:2011-07-21 16:19:25

标签: sql tsql

我有两张表

第一张表

FtID         ItemName            Days
---------------------------------------
1            Drive                10
2            Run                  5
3            Read                 21

第二张表

StID    FtID        Completed (bit)         DateTime  
-----------------------------------------------------

1        1             0                    07/11/2011
2        1             1                    08/11/2011 
3        1             1                    09/11/2011 
4        1             0                    10/11/2011 
5

我需要从两个表中选择并获取数据,如下所示

ItemName Days DaysCompleted DaysIncompleted  PercentageCompletion     DaysLeft
---------------------------------------------------------------------------------------          
Drive     10    2              2                40%                   6

3 个答案:

答案 0 :(得分:1)

SELECT 
      t1.ItemName,
      t1.Days,
      SUM(Cast(t2.Completed as integer))  DaysCompleted ,
      COUNT(t2.StID) -  SUM(Cast(t2.Completed as integer)) DaysIncompleted  ,
      (COUNT(t2.StID) * 100 / t1.Days))  PercentageCompletion     ,
      t1.Days - SUM(CASE WHEN DateTime > GetDate() THEN 1 ELSE 0)) DaysLeft
FROM 
     table1 t1 
     INNER JOIN table2 t2
     ON t1.ftId = t2.ftID
GROUP BY
      t1.ItemName,
      t1.Days

正如JNK所指出的,如果Completed确实是一个BIT,你需要转换为一个整数(或者使用SUM / CASE作为他的答案)。如果你想要40,我输出Percentage Complete为.40,那么如果t1.Days不是小数,你需要转换为十进制。

答案 1 :(得分:0)

SELECT
   ItemName,
   Days,
   sum(cast(Completed as integer) as DaysCompleted,
   (max(DateTime) - min(DateTime)) - sum(cast(Completed as integer) as Days Incompleted,
   (Days - (max(DateTime) - min(DateTime))) / Days as Percentage Completion,
   Days - (max(DateTime) - min(DateTime)) as DaysLeft
FROM
   Table_1 T1 INNER JOIN Table_2 T2 ON T1.FtID = T2.FtID
GROUP BY
   ItemName,
   Days

从此开始/玩它

答案 2 :(得分:0)

尝试:

SELECT  f.ItemName, 
        f.Days,
        SUM(CASE WHEN s.Completed = 1 THEN 1 ELSE 0 END) as DaysCompleted,
        SUM(CASE WHEN s.completed = 0 THEN 1 ELSE 0 END) as DaysIncompleted,
        CAST((COUNT(s.completed)/f.days) as DECIMAL(10,8)) as PercentageComplete,
        (f.days-(COUNT(s.completed)) as DaysLeft
FROM FirstTable F
INNER JOIN SecondTable S
    ON F.FTID = S.FTID
GROUP BY f.itemname, f.days