Mysql:如何计算两个平均值之间的差异?

时间:2015-11-05 16:34:17

标签: mysql sql

我有一张桌子:

struct BstNode{
    int value;
    struct BstNode* left;
    struct BstNode* right;
};

struct BstNode *root; 

struct BstNode* insertNode(struct BstNode* root, int data){
    if(data <= root->value)
        root->left = insertNode(root->left, data);
    else
        root->right = insertNode(root->right, data);

    printf("%d  ",root->value);
    return root;
}


void create(struct BstNode* root){ 
    int data;
    if(root == NULL){
        //create the root node
        printf("\nInside create");
        root = (struct BstNode*) malloc(sizeof(struct BstNode));
        printf("\nData :: ");
        scanf("%d",&data);
        root->value = data;
        root->left = NULL;
        root->right = NULL;
    }
    else{
        printf("\nCalling insertNode()");
        printf("\nData :: ");
        scanf("%d",&data);
        root = insertNode(root, data);  // The program hangs up here : the very first time this line is executed
        printf("\nCalled insert");
    }
}

int main(){
    root = NULL;
    int i;
    for(i=0;i<5;i++){
        create(root);
        printf("%d ",root->value); // For checking the value 
    }
    return 0;
}

我想计算美国的平均值(得分) - 中国的平均值(得分)。

我试过了

+------------+--------------+-------+------------+
| Name       | Nation       | Score | Game_date  |
+------------+--------------+-------+------------+
| Ginobili   | Argentina    |    48 | 2005-01-21 |
| Irving     | Australia    |    44 | 2014-04-06 |
| Kirilenko  | Soviet Union |    31 | 2006-11-11 |
| Kobe       | USA          |    81 | 2006-01-22 |
| LeBron     | USA          |    52 | 2014-12-06 |
| Mutombo    | Congo        |    39 | 1992-02-03 |
| Nowitzki   | Germany      |    48 | 2011-05-18 |
| PauGasol   | Spain        |    46 | 2015-01-11 |
| SteveNash  | Canada       |    42 | 2006-12-08 |
| TonyParker | France       |    55 | 2008-11-06 |
| YaoMing    | China        |    41 | 2009-02-23 |
| YiJianlina | China        |    31 | 2010-03-27 |
+------------+--------------+-------+------------+

但这是错的!

1 个答案:

答案 0 :(得分:0)

您可以使用AVGCASE WHEN

SELECT AVG(CASE WHEN nation = 'USA' THEN score END) -
       AVG(CASE WHEN nation = 'China' THEN score END) AS result
FROM nba
WHERE nation IN ('USA', 'China');

另一种选择是使用UNION

SELECT SUM(sub.r) AS result
FROM ( SELECT avg(score) AS r
       from nba 
       where nation = 'USA' 
       UNION ALL
       SELECT -avg(score) 
       from nba 
       where nation = 'China') AS sub
相关问题