我的查询看起来像这样
CREATE TABLE work_pr.op1 AS
SELECT DISTINCT level1_idnt
,org_sales_price
FROM md1.item_lv1_org_price_m
WHERE fr_cntry_cde = '01';
CREATE TABLE work_pr.op2 AS
SELECT level1_idnt
,org_sales_price
FROM work_pr.op1
WHERE org_sales_price IS NOT NULL;
CREATE TABLE work_pr.final_op AS
SELECT level1_idnt
,avg(org_sales_price) AS op
FROM work_pr.op2
GROUP BY level1_idnt;
我希望步骤处于相同的顺序,除了我不想创建work_pr.op1和work_pr.op2表。如何在sql中缩短此过程。我是sql的新手,非常感谢任何帮助
答案 0 :(得分:1)
您可以使用嵌套选择来创建单个表,最后一个:
CREATE TABLE work_pr.final_op AS
SELECT level1_idnt
,avg(org_sales_price) AS op
FROM (
SELECT level1_idnt
,org_sales_price
FROM (
SELECT DISTINCT level1_idnt
,org_sales_price
FROM md1.item_lv1_org_price_m
WHERE fr_cntry_cde = '01'
) result_set_1
WHERE org_sales_price IS NOT NULL
) result_set_2
GROUP BY level1_idnt;
正如@GordonLinoff所提到的,SELECT
可以简化,您可以在答案中使用。{/ p>
答案 1 :(得分:1)
您可以将查询编写为:
SELECT level1_idnt, AVG(org_sales_price) as op
FROM (SELECT DISTINCT level1_idnt, org_sales_price
FROM md1.item_lv1_org_price_m
WHERE fr_cntry_cde = '01' AND org_sales_price IS NOT NULL
) l
GROUP BY level1_idnt;
但是,子查询中不应该有DISTINCT
。通常,查询将简化为:
SELECT level1_idnt, AVG(org_sales_price) as op
FROM md1.item_lv1_org_price_m
WHERE fr_cntry_cde = '01' AND org_sales_price IS NOT NULL
GROUP BY level1_idnt;