如何将 Apache Superset 中的过滤器应用于不在最终查询中的列

问题描述 投票:0回答:1

我目前正在使用 Apache Superset,并遇到了一个特定的挑战。我需要对最终查询输出中不存在但存在于 FROM 子句中的子查询中的列应用过滤器。有人对如何实施这个有见解吗?当我解决这个问题时,任何指导或示例将不胜感激。

提前感谢您的帮助!

只有我期待解释或可能性

postgresql data-analysis apache-superset
1个回答
0
投票

如果你有这样的情况:

WITH    -- S a m p l e    D a t a :
    items (ID, ITEM_NAME) As
      ( Select 1, 'Item 1' Union All 
        Select 2, 'Item 2' Union All 
        Select 3, 'Item 3' 
      ),
   prices (ID, PRICE, ACTIVE) AS
      ( Select 1, 10, 'No'  Union All 
        Select 1, 12, 'Yes' Union All 
        Select 2, 25, 'Yes' Union All 
        Select 3, 20, 'No'  Union All 
        Select 3, 22, 'Yes' 
    )

...使用子查询选择 PRICE_DIFF_PCT 列,并且您希望将结果过滤为仅差异大于 10% 的行,而主(外部)查询的选择列表中没有该列 - 将未选择的列放入 where 子句结果中有错误...

Select  p.ID, p.ITEM_NAME, p.PRICE_NEW, p.PRICE_OLD
From    ( Select i.ID, i.ITEM_NAME,
                 p1.PRICE as PRICE_NEW, p2.PRICE as PRICE_OLD,
                 (p1.PRICE - p2.PRICE) * 100 / p2.PRICE as PRICE_DIFF_PCT
          From   items i
          Left Join prices p1 ON(p1.ID = i.ID And p1.ACTIVE = 'Yes')
          Left Join prices p2 ON(p2.ID = i.ID And p2.ACTIVE = 'No')
        ) p
Where   PRICE_DIFF > 10
/*    R e s u l t :
ERROR:  column "price_diff" does not exist
LINE 22: Where   PRICE_DIFF > 10
*/

...执行此操作的一个选项是将子查询声明为 cte(将其命名为 Price_diffs),并在主查询的 from 子句中使用它,并在 where 子句中使用 EXISTS() ...

   price_diffs AS     -- Declare your subquery as a cte
     ( Select i.ID, i.ITEM_NAME,
              p1.PRICE as PRICE_NEW, p2.PRICE as PRICE_OLD,
             (p1.PRICE - p2.PRICE) * 100 / p2.PRICE as PRICE_DIFF_PCT
       From   items i
       Left Join prices p1 ON(p1.ID = i.ID And p1.ACTIVE = 'Yes')
       Left Join prices p2 ON(p2.ID = i.ID And p2.ACTIVE = 'No')
     )
--    M a i n    S Q L :
Select  pd.ID, pd.ITEM_NAME, pd.PRICE_NEW, pd.PRICE_OLD
From    price_diffs pd
Where   EXISTS(Select 1 From price_diffs Where ID = pd.ID And PRICE_DIFF_PCT > 10)
/*    R e s u l t :
id  item_name   price_new   price_old
--  ---------   ---------   ---------
 1  Item 1             12          10   */
© www.soinside.com 2019 - 2024. All rights reserved.