我有一张不同公司的许多产品的所有销售记录的表格。每个记录都包括出售的产品,出售的价格,出售该产品的公司名称(请注意,可以以任何可能的价格出售相同的产品)。表结构示例:
id | product | sales_price | company
---+---------+-------------+---------
1 | prod122 | 123376456 | abcSales
2 | prod123 | 345676433 | xyzSales
3 | prod122 | 346876543 | xyzSales
4 | prod124 | 124688533 | wpwSales
我正试图找出哪家公司的最昂贵产品的销量最高。换句话说,我想编写一个查询,查找平均价格最高的产品,将其命名为PRODUCTX
,然后查找销售数量最高的PRODUCTX
的公司,并将其命名为{{1 }}。
结果应为一行,其中一列显示COMPANYX
,另一列显示PRODUCTX的销售量。
非常感谢您的帮助。
答案 0 :(得分:0)
您可以尝试以下方法:
WITH DATAA (id,product,sales_price,company)
AS
(
SELECT 1, 'prod122', 123376456, 'abcSales' FROM DUAL UNION ALL
SELECT 2, 'prod123', 345676433, 'xyzSales' FROM DUAL UNION ALL
SELECT 3, 'prod122', 346876543, 'xyzSales' FROM DUAL UNION ALL
SELECT 4, 'prod124', 124688533, 'wpwSales' FROM DUAL
)
SELECT
D.COMPANY,
D.PRODUCT,
T.AVG_PRICE,
COUNT(1) NO_OF_PRODUCT
FROM
DATAA D
JOIN (
SELECT
AVG(SALES_PRICE) AVG_PRICE,
PRODUCT
FROM
DATAA
GROUP BY
PRODUCT
ORDER BY
AVG_PRICE DESC
FETCH FIRST ROWS ONLY
) T ON ( T.PRODUCT = D.PRODUCT )
GROUP BY
D.COMPANY,
D.PRODUCT,
T.AVG_PRICE
ORDER BY
NO_OF_PRODUCT DESC
FETCH FIRST ROWS ONLY;
输出
答案 1 :(得分:0)
如果多种产品并列最高平均售价怎么办? 如果多家公司以平均销售价格最高的产品获得最多的销售额,那又如何呢?
以下查询说明了这些情况。可以调整示例数据中的sales_price以检查不同的情况。
WITH sample (id,product,sales_price,company)
AS
(
SELECT 1, 'prod100', 10, 'Company 1' FROM DUAL UNION ALL
SELECT 2, 'prod122', 10, 'Company 1' FROM DUAL UNION ALL
SELECT 3, 'prod123', 10, 'Company 2' FROM DUAL UNION ALL
SELECT 4, 'prod123', 10, 'Company 2' FROM DUAL UNION ALL
SELECT 5, 'prod123', 10, 'Company 3' FROM DUAL UNION ALL
SELECT 6, 'prod123', 10, 'Company 3' FROM DUAL
),
-- Top product(s) by average sales price
top_product AS (
SELECT *
FROM (-- Rank the average sales price (ASP) by product
SELECT product,
AVG(sales_price) avg_sales_price,
RANK() OVER (ORDER BY AVG(sales_price) DESC) avg_sales_price_rank
FROM sample
GROUP BY product
)
WHERE avg_sales_price_rank = 1
),
-- Sales count by company, product
comp_prod_sales AS (
SELECT company,
product,
COUNT(*) sales_count
FROM sample
GROUP BY company,
product
)
-- Top sales of top product(s)
SELECT company,
product,
avg_sales_price,
sales_count
FROM (SELECT comp_prod_sales.*,
top_product.avg_sales_price,
RANK() OVER (PARTITION BY top_product.product ORDER BY sales_count DESC) sales_count_rank
FROM top_product,
comp_prod_sales
WHERE comp_prod_sales.product = top_product.product)
WHERE sales_count_rank = 1;