Im trying to calculate the percentages开发者_运维百科 of selected fields from tables. Within the fields that data is numeric but I want to show the percentage value. Please help.
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); }
}
Use subselect like this(this is PostgreSQL query)
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
Same Concept in 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 + ")
精彩评论