SQL用于计算列等于特定值的组中的行

时间:2017-01-03 23:41:21

标签: sql oracle select count

我有一个包含CMDNAME,TIME和FAILED列的表。有许多行具有相同的CMDNAME值。 TIME列只是事务的时间戳。 FAILED列是" Y"或" N"。

我希望我的结果是,对于CMDNAME的每个不同的值,行的比率为FAILED =' Y'到总行数(对于相同的CMDNAME值)。

我可以接受以下内容:

 package main;

import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class  MainMethod extends Application{

private Stage primaryStage;
private VBox MainLayout;
private AnchorPane submain;


    @Override
    public void start(Stage primaryStage) throws IOException{
        this.primaryStage = primaryStage;
        this.primaryStage.setTitle("Nursery");
        showMainView();
         showMainPane();
    }

    private void showMainView() throws IOException{
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(MainMethod.class.getResource("../controller/Add_child.fxml"));
        MainLayout = loader.load();
        Scene secne = new Scene(MainLayout);
        primaryStage.setScene(secne);
        primaryStage.show();
    }

    private void showMainPane() throws IOException{
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(MainMethod.class.getResource("../controller/Add_ChildPane.fxml"));
        VBox mainitems = loader.load(); // I am Struggling here I think


    }

    public static void main (String[] args){
        System.out.println("sfdf");
        launch(args);
    }
}

对于每个唯一的CMDNAME值,我给出两行,其中一行用" N"算和#34; Y"计数。如果我无法找出更直接的计算方法,我可以使用这个,进行一些中间计算。

2 个答案:

答案 0 :(得分:2)

与许多聚合函数一样,

count会跳过null个。您可以使用此属性并计算仅报告case行的failed='Y'表达式:

SELECT   cmdname,
         COUNT(*) AS all_rows
         COUNT(CASE failed WHEN 'Y' THEN 1 END) AS only_failures,
         COUNT(CASE failed WHEN 'Y' THEN 1 END) / COUNT(*) AS failure_ratio
FROM     mytbale
GROUP BY cmdname

答案 1 :(得分:1)

一种方法是使用count窗口函数。

select distinct CMDNAME, 
1.0*count(case when failed = 'Y' then 1 end) over(partition by CMDNAME)
/count(*) over(partition by CMDNAME) as groupCount 
from TABLE 

或使用条件聚合。

select CMDNAME, 
1.0*count(case when failed = 'Y' then 1 end)/count(*) as groupCount 
from TABLE 
group by CMDNAME