SQL-计算数据库表值的百分比

时间:2011-01-16 23:44:47

标签: c# sql ms-access

我试图计算表格中所选字段的百分比。在数据是数字的字段中但我想显示百分比值。请帮忙。

    private void btnpics_Click(object sender, EventArgs e)
    {
        try
        {
            myCon.Open();
            string queryString = "SELECT FoodType.Description,FoodType.Calories, FoodType.Carbohydrate, FoodType.Fat, FoodType.Protein FROM [FoodType], [Meal] WHERE (Meal.UserID =" + userid.Text + ") AND (Meal.MealDate =" + date.Text + ");";
            MessageBox.Show(queryString);
            loadDataGrid(queryString);
        }
        catch (Exception ex) { MessageBox.Show(ex.Message); }
    }

2 个答案:

答案 0 :(得分:0)

使用这样的subselect(这是PostgreSQL查询)

CREATE TABLE test (a numeric(10, 2), b numeric(10,2));
INSERT INTO test values(3, 5);

SELECT a, b, 
       a*100/sum AS a_percentage, 
       b*100/sum AS b_percentage
  FROM (SELECT a+b as sum, a, b 
        FROM test) sub

答案 1 :(得分:0)

MSSQL中的相同概念

SELECT
  FoodType.Description,
  FoodType.Calories,
  FoodType.Carbohydrate,
  FoodType.Fat,
  FoodType.Protein,
  FoodType.Calories / A.SumCalories * 100 AS CaloriesPercentage,
  FoodType.Carbohydrate / A.SumCarbohydrate * 100 AS CarbohydratePercentage,
  FoodType.Fat / A.SumCalories * 100 AS FatPercentage,
  FoodType.Protein / A.SumProtein * 100 AS ProteinPercentage
FROM [FoodType]
JOIN [Meal] ON FoodType.ID = Meal.FoodTypeID --Not sure on your table schema here.
JOIN 
(
  SELECT
    FoodType.Description,
    SUM(FoodType.Calories) AS SumCalories,
    SUM(FoodType.Carbohydrate) AS SumCarbohydrate,
    SUM(FoodType.Fat) AS SumFat,
    SUM(FoodType.Protein) AS SumProtein
  FROM [FoodType],[Meal]
  WHERE (Meal.UserID =" + userid.Text + ") AND (Meal.MealDate =" + date.Text + ")
  GROUP BY FoodType.Description
) A ON FoodType.Description = A.Description --You should use FoodTypeID if it exists
WHERE (Meal.UserID =" + userid.Text + ") AND (Meal.MealDate =" + date.Text + ")