我有一张表,该表显示了商店的名称以及订单来自的各个城市,该表取自PostgreSQL中的json查询。它基于一项调查,在该调查中,我们还查看了该调查被查看了多少次以及有多少回应。我正在尝试在表格中创建另一列,该列主要计算每个商店的每个城市的订单数量。 这里显示了一个示例列表,其中商店名称在左侧,而城市在右侧:
1. Glossier | New York | 7 | 6
2. Glossier | New York | 7 | 6
3. Glossier | Chicago | 7 | 6
4. Glossier | Boston | 7 | 6
5. Glossier | New York | 7 | 6
6. Glossier | Chicago | 7 | 6
7. Sephora | New York | 10 | 8
8. Sephora | Baltimore | 10 | 8
9. Sephora | New York | 10 | 8
10. Sephora | Boston | 10 | 8
11. Sephora | New York | 10 | 8
12. Sephora | Baltimore | 10 | 8
13. Sephora | Chicago | 10 | 8
14. Sephora | San Francisco | 10 | 8
我一直在使用的代码是:
WITH
cities AS (
SELECT context->>'city' AS city,
context->>'shop_id' AS shopid
FROM public.analytics_events
),
views AS (
SELECT
DISTINCT ON (ref_id) ref_id,
CASE WHEN context->>'order_total' IS NULL THEN 0
ELSE cast(context->>'order_total' AS NUMERIC)
END AS total,
context->>'shop_id' AS shop_id
FROM public.analytics_events
),
view_counts AS (
SELECT COUNT(DISTINCT ref_id) AS views, SUM(total)
AS volume, shop_id
FROM views
GROUP BY shop_id
),
response_counts AS (
SELECT COUNT(survey_responses.id) AS responses,
surveys.shop_id AS shop_id, surveys.question,
surveys.id AS surveyid
FROM public.survey_responses
LEFT JOIN public.surveys
ON surveys.id = survey_responses.survey_id
GROUP BY surveys.shop_id, surveys.question, surveyid
)
SELECT
name,
CASE WHEN views IS NULL THEN 0 ELSE views END,
CASE WHEN responses IS NULL THEN 0 ELSE responses END,
city,
COUNT(*)
FROM public.shops
LEFT JOIN view_counts ON shops.id = view_counts.shop_id
LEFT JOIN response_counts ON shops.id = response_counts.shop_id
LEFT JOIN cities on shops.id = cities.shopid
GROUP BY name, city;
但是,我现在停留在如何创建下一步上。
答案 0 :(得分:1)
我怀疑您只是想group by
:
WITH cities AS (
SELECT context->>'city' AS city, context->>'shop_id' AS shopid
FROM analytics
)
SELECT name, city, COUNT(*)
FROM shops LEFT JOIN
cities
ON shops.id = cities.shopid
GROUP BY name, city;