对于2014年的每个月,仅显示从汽车销售生成的总利润(即使用购买的价格和商定价格)。
表:
(VIN, dateAcquired, yearBuilt, purchasedPrice, askingPrice, currentMileage, modelNo)
(VIN, custID, agentID, dateOfSale, agreedPrice)
select c.dateacquired, st.agreedprice - c.purchasedprice as "Total Profit"
from salestransaction st, car c
where c.VIN = st.VIN
and extract(year from c.dateacquired) = '2014'
group by extract(month from c.dateacquired), st.agreedprice - c.purchasedprice;
有人可以告诉我我做错了吗?
我收到以下错误:
不是第01行的GROUP BY表达式
答案 0 :(得分:1)
SELECT
列表中不属于聚合函数的列应与表格中的表格准确匹配。
这意味着c.dateacquired
不等于extract(month from c.dateacquired)
,因此会给您错误。
您希望按月分组,但是您尝试选择确切的,而不是截断的date
。
假设您希望选择月份,请更正代码:
select extract(month from c.dateacquired), st.agreedprice - c.purchasedprice as "Total Profit"
from salestransaction st, car c
where c.VIN = st.VIN
and extract(year from c.dateacquired) = '2014'
group by extract(month from c.dateacquired), st.agreedprice - c.purchasedprice;
这只是对您的查询的修复,但我认为结果仍然不是您正在寻找的。您可能希望在该总计上使用聚合函数sum()
。
答案 1 :(得分:0)
SELECT EXTRACT(month FROM c.dateacquired), SUM(st.agreedprice - c.purchasedprice) AS "Total Profit"
FROM salestransaction st
INNER JOIN car c ON st.VIN = c.VIN
WHERE EXTRACT(year FROM c.dateacquired) = '2014'
GROUP BY EXTRACT(month FROM c.dateacquired)
答案 2 :(得分:0)
一些问题:
SUM
所有利润才能获得总利润。GROUP BY
时,您需要SELECT
GROUP BY
中的确切陈述或使用汇总功能。像这样:
SELECT TRUNC( s.dateOfSale, 'MM' ) AS month_aquired,
SUM( st.agreedprice - c.purchasedprice ) as "Total Profit"
FROM salestransaction st,
car c
WHERE c.VIN = st.VIN
AND EXTRACT( year FROM s.dateOfSale ) = 2014
GROUP BY
TRUNC( s.dateOfSale, 'MM' );
或者您可以将TRUNC( s.dateOfSale, 'MM' )
替换为顶部和底部的EXTRACT( month FROM s.dateOfSale )
。