我与PROC SQL在SAS的工作和我的PROC SQL查询之一的行为非常奇怪:别名和组通过SAS PROC SQL语句
我有一个大的数据集(约1万行),其看起来是这样的:
apple_key profit price cost months date
golden_d 0.03 12 4 3 01/12
golden_d 0.03 8 0 2 01/12
granny_s 0.05 15 5 5 02/12
red_d 0.04 13 0 1 01/12
golden_d 0.02 1 2 12 03/14
在我运行下面的查询这组数据:
%let picking_date = 01/12; /* I simplify here - this part of my code definitely works */
proc sql;
CREATE TABLE output AS
SELECT
(CASE apple_key
WHEN "golden_d" THEN 1
WHEN "granny_s" THEN 2
WHEN "red_d" THEN 3
END) AS apple_id,
apple_key AS apple_name,
(CASE WHEN cost= 0 THEN 0
ELSE 1
END) AS cost_flag,
(CASE
WHEN CEIL(months/2) < 5 THEN CEIL(months/2)
ELSE 5
END) AS age,
"McDonalds" as farm,
sum(profit*price)/sum(price) as price_weighted_profit
FROM input_table
WHERE date = "&picking_date."d
AND price > cost
AND cost >= 0
AND cost >= 0
GROUP BY apple_id, apple_name, cost_flag, age, farm
;
run;
当我运行此我GROUP BY
声明不起作用。我为单个组获得了一堆条目 (其中apple_id,apple_name,cost_flag,年龄和农场都是相同的,但是我的聚合不起作用)。
但是,当我分别运行GROUP BY(如下所示)时,一切正常。我为每个组获得一个具有“价格加权利润”的条目:
proc sql;
CREATE TABLE output_tmp AS
SELECT
(CASE apple_key
WHEN "golden_d" THEN 1
WHEN "granny_s" THEN 2
WHEN "red_d" THEN 3
END) AS apple_id,
apple_key AS apple_name,
(CASE WHEN cost= 0 THEN 0
ELSE 1
END) AS cost_flag,
(CASE
WHEN CEIL(months/2) < 5 THEN CEIL(months/2)
ELSE 5
END) AS age,
"McDonalds" as farm
FROM input_table
WHERE date = "&picking_date."d
AND price > cost
AND cost >= 0
AND cost >= 0
;
CREATE TABLE output AS
SELECT
apple_id,
apple_name,
cost_flag,
age,
farm,
sum(profit*price)/sum(price) as price_weighted_profit
FROM output_tmp
GROUP BY apple_id, apple_name, cost_flag, age, farm
;
quit;
为什么会发生这种情况?我该如何解决它?这是让我有点疯狂......谢谢前面的帮助
你想通过做一组来计算计数或总和? – Teja
对不起。忘记将摘要函数语句移至第二个“create table”语句。现在应该是正确的。我在这里试图计算“price_weighted_profit” – MRR
您希望从样本输入中得到什么结果?你得到什么输出? – Tom