我有一个名为kcal(int)的字段,我想对不同条件的值求和。如果我可以先选择kcal字段,它应该是这样的,但我只想要总和的值,其中列符合某些条件。
SELECT kcal AS k1, kcal AS k2, kcal AS k3, (k1 + k2 + k3) FROM table WHERE ...
编辑:我有这张桌子
CREATE TABLE [dbo].[Menu] (
[id_product] INT NOT NULL,
[product_name] NCHAR (50) NOT NULL,
[description] TEXT NULL,
[price] INT NOT NULL,
[kcal] INT NOT NULL,
[dish] INT NOT NULL,
PRIMARY KEY CLUSTERED ([id_product] ASC)
);
我希望显示3 product_name的所有组合(每个具有不同的菜值(可以是1,2或3)),每3种组合的total_kcal,每3种组合的总价,条件是价格< 50的总和和kcal的总和<为此,我写了这个:
SELECT (SELECT product_name FROM Menu WHERE dish = 1) AS Dish1, (SELECT product_name FROM Menu WHERE dish = 2) AS Dish2, (SELECT product_name FROM Menu WHERE dish = 3) AS Dish3, SUM(kcal) AS Total_Kcal , SUM(price) as Total_Price FROM Menu WHERE dish IN (1, 2, 3) GROUP BY dish HAVING SUM(pret) < 50 AND SUM(kcal) < 2000
它的工作正常,但总和不对应的问题。
答案 0 :(得分:1)
可能有一种更好的方法,但这听起来像是一个CROSS JOIN,对我来说有很多条件:
SELECT
m1.product_name
,m2.product_name
,m3.product_name
,(m1.kcal + m2.kcal + m3.kcal) AS CombinedKcal
,(m1.price + m2.price + m3.price) AS CombinedPrice
FROM
Menu AS m1
,Menu AS m2
,Menu AS m3
WHERE
-- Ensure combinations include each dish only once.
(m1.id_product <> m2.id_product AND m2.id_product <> m3.id_product AND m3.id_product <> m1.id_product)
AND
-- Ensure combinations include a dish 1, a dish 2 and a dish 3
(m1.dish = 1 AND m2.dish = 2 AND m3.dish = 3)
AND
-- Ensure Combined Calories is less than 2000
(m1.kcal + m2.kcal + m3.kcal) < 2000
AND
-- Ensure Combined Price is less than 50
(m1.price + m2.price + m3.price) < 50
答案 1 :(得分:0)
使用基本列名称重复表达式或使用子查询:
SELECT t.*, (k1 + k2 + k3)
FROM (SELECT kcal AS k1, kcal AS k2, kcal AS k3
FROM table
WHERE ...
) t;
为什么不在没有子查询的情况下重复列别名?简单。 SQL不保证SELECT
中表达式的评估顺序。因此,最后一个表达式可能是第一个执行的表达式。 。 。并且k1
不会被人知道。
我还应该注意,使用这样的子查询会产生额外的开销,因为MySQL实现了子查询。您应该在没有子查询的情况下使用(kcal + kcal + kcal)
以获得更好的性能。