计算两列SQL之间的划分

时间:2014-11-18 22:31:11

标签: sql sql-server

我在计算SQL中两列之间的分区时遇到了一些麻烦。 到目前为止,我写了这个:

SELECT s.ccode, (1-(ygrade/xnumber))*100 AS flow
FROM
( SELECT COUNT(s.ccode) AS xnumber
FROM Studied s
) x
JOIN
(SELECT COUNT(grade) as ygrade
FROM Studied s
WHERE grade <> 'U'
) y on x.ccode = y.ccode

这显然是错误的。我有一个包含三列spnr,ccode和grade的表。我想计算所有课程的流量,即1-amountGrade = U / amountAllgrades。应该为每门课程进行计算,这样我就可以得到一个专栏“#flow;&#39;每个课程的流量百分比。

提前感谢您的帮助!!

2 个答案:

答案 0 :(得分:2)

给它一个旋转。我相信这就是你所寻求的。

SELECT
    x.ccode
    , (CAST(ygrade as float)/CAST(xnumber AS FLOAT))*100 AS flow
FROM
(
    SELECT ccode, COUNT(s.ccode) AS xnumber
    FROM Studied s
    GROUP BY ccode
) x
    JOIN
    (
        SELECT ccode, COUNT(grade) as ygrade
        FROM Studied s
        WHERE grade <> 'U'
        GROUP BY ccode
    ) y
        on x.ccode = y.ccode
;

答案 1 :(得分:0)

您需要一些group by s并修复整数除法。我猜这是你想要的查询:

SELECT x.ccode, (1-(cast(ygrade as float)/xnumber))*100 AS flow
FROM (SELECT ccode, COUNT(s.ccode) AS xnumber
      FROM Studied s
      GROUP BY ccode
     ) x JOIN
     (SELECT ccode, COUNT(grade) as ygrade
      FROM Studied s
      WHERE grade <> 'U'
      GROUP BY ccode
     ) y
     on x.ccode = y.ccode;

有更简单的方法可以执行此操作,但这是对您的查询的修复。