很酷,所以这是一个“从一个地方获取两个结果,然后组合结果”的查询?如果您可以保证具有唯一 customer_id 的客户表,这应该可以工作。我认为当天总数的百分比方法会比分子/分母更好,因为不会有 0 个“新”客户和 0 个“旧”客户的日子吗?
我也不是很清楚,新客户还是老客户哪个更重要?这提供了新客户的百分比,您可以根据需要切换以显示老客户的百分比。
------- just some fake data - you won't need this because you have the real thing
WITH CUSTOMER_TABLE AS (
SELECT 1 AS customer_id , CAST('2017-08-01' AS DATE) AS first_order_date , CAST('2018-07-05' AS DATE) AS last_order_date UNION
SELECT 2 , '2018-07-01' , '2018-07-06' UNION
SELECT 3 , '2018-07-01' , '2018-07-07' UNION
SELECT 4 , '2018-07-01' , '2018-07-08' UNION
SELECT 5 , '2018-06-01' , '2018-07-09' UNION
SELECT 6 , '2018-05-31' , '2018-07-10' UNION
SELECT 7 , '2018-07-01' , '2018-07-11' UNION
SELECT 8 , '2018-07-01' , '2018-07-12' UNION
SELECT 9 , '2018-07-01' , '2018-07-13' UNION
SELECT 10 , '2018-07-01' , '2018-07-14' UNION
SELECT 11 , '2018-07-01' , '2018-07-15' UNION
SELECT 12 , '2018-03-04' , '2018-07-16' UNION
SELECT 13 , '2018-01-01' , '2018-07-17' UNION
SELECT 14 , '2018-07-01' , '2018-07-17' UNION
SELECT 15 , '2018-07-01' , '2018-07-17' UNION
SELECT 16 , '2018-01-01' , '2018-07-18' UNION
SELECT 17 , '2018-02-01' , '2018-07-18' UNION
SELECT 18 , '2018-07-02' , '2018-07-18' UNION
SELECT 19 , '2018-07-01' , '2018-07-18'
)
SELECT last_order_date ,
------ note the "1.00" forcing PostgreSQL to return a decimal result
1.00 * (count_of_new_customers)/(count_of_old_customers + count_of_new_customers ) AS percentage_of_new_customers ,
count_of_old_customers , count_of_new_customers ,
count_of_old_customers + count_of_new_customers AS total_customers_for_the_day
FROM
(
SELECT last_order_date ,
CAST(COUNT (CASE WHEN DATEDIFF(DAY, first_order_date , last_order_date) > 30 THEN 'old customer' END ) AS integer) AS count_of_old_customers ,
CAST(COUNT (CASE WHEN DATEDIFF(DAY, first_order_date , last_order_date) <= 30 THEN 'new customer' END ) AS integer) AS count_of_new_customers
----replace CUSTOMER_TABLE with your actual schema.table
FROM CUSTOMER_TABLE
GROUP BY last_order_date
)
----- here is the descending last_order_date you wanted
ORDER BY last_order_date DESC