如何在 redash 中插入基于计数结果的查询过滤器

How to insert query filter based on count result in redash

我认为这是一个简单的问题,但由于我不熟悉 redash,所以似乎很难。

我有一个红色的查询,

SELECT si.variant_id,
       v.sku,
       COUNT(CASE
                 WHEN a.viewable_type = 'Spree::Variant' THEN a.id
             END) AS photo
FROM spree_stock_items si
LEFT JOIN spree_stock_locations sl ON sl.id = si.stock_location_id
LEFT JOIN spree_assets a ON si.variant_id = a.viewable_id
LEFT JOIN spree_variants v ON v.id = si.variant_id
WHERE-- viewable_type = 'Spree::Variant'
sl.name='{{store_location}}'
  AND si.deleted_at IS NULL
  AND sl.country_id = '2'
GROUP BY 1,
         2
ORDER BY 1
LIMIT 200000

结果如下:

截至目前,我可以在 store location 上过滤结果。但现在我想根据列 photo 添加 query filter。我该怎么做?基本上我想通过 store locationphoto 列中的计数过滤 redash 仪表板中的结果。

您可以使用 having 子句 - 但它需要重复聚合表达式。例如:

SELECT si.variant_id,
       v.sku,
       COUNT(a.id) FILTER(WHERE a.viewable_type = 'Spree::Variant') AS photo
FROM spree_stock_items si
LEFT JOIN spree_stock_locations sl ON sl.id = si.stock_location_id
LEFT JOIN spree_assets a ON si.variant_id = a.viewable_id
LEFT JOIN spree_variants v ON v.id = si.variant_id
WHERE-- viewable_type = 'Spree::Variant'
    sl.name='{{store_location}}'
    AND si.deleted_at IS NULL
    AND sl.country_id = '2'
GROUP BY 1, 2
HAVING COUNT(a.id) FILTER(WHERE a.viewable_type = 'Spree::Variant') > 1
ORDER BY 1
LIMIT 200000

请注意,我重写了 count() 以使用标准 filter 子句,这使语法更整洁。

或者,您可以在外部查询中使用子查询和 WHERE 子句:

SELECT *
FROM (
    SELECT si.variant_id,
           v.sku,
           COUNT(a.id) FILTER(WHERE a.viewable_type = 'Spree::Variant') AS photo
    FROM spree_stock_items si
    LEFT JOIN spree_stock_locations sl ON sl.id = si.stock_location_id
    LEFT JOIN spree_assets a ON si.variant_id = a.viewable_id
    LEFT JOIN spree_variants v ON v.id = si.variant_id
    WHERE-- viewable_type = 'Spree::Variant'
    sl.name='{{store_location}}'
      AND si.deleted_at IS NULL
      AND sl.country_id = '2'
    GROUP BY 1, 2
) t
WHERE photo > 1
ORDER BY 1
LIMIT 200000