查找构成聚合查询的值

时间:2017-09-23 18:18:24

标签: unit-testing plsql

我在plsql

中有以下表格
Company | StoreNum | Sku | Units | Dollars
  • 首先查询:

    select company, storeNum, sku, SUM(units)  AS Units, SUM(dollars) AS dollars
    FROM Sales
    GROUP BY company, storeNum, sku
    
  • 第二个查询:

    select COUNT(DISTINCT company), COUNT(DISTINCT(storeNum), sku, 
    SUM(units)  AS Units, SUM(dollars) AS dollars
    FROM Sales
    GROUP BY sku
    HAVING COUNT(DISTINCT company) >= 2
    

第二个查询获得sku的总计,其中至少有两个companies正在销售sku。我需要一种方法来找出哪家公司,商店组成这个清单?

1 个答案:

答案 0 :(得分:0)

您可以使用LISTAGG获取以逗号分隔的公司列表和商店列表,如下所示。

SELECT LISTAGG(company,',') WITHIN GROUP (
ORDER BY company) company_list,
  LISTAGG(StoreNum,',') WITHIN GROUP (
ORDER BY storeNum) Store_list,
  COUNT(DISTINCT company),
  COUNT(DISTINCT storeNum),
  sku,
  SUM(units)   AS Units,
  SUM(dollars) AS dollars
FROM Sales
GROUP BY sku
HAVING COUNT(DISTINCT company) >= 2;

注意:这适用于Oracle 11g及更高版本。