在SQL中从客户ID中选择城市

时间:2018-06-14 12:38:15

标签: sql postgresql

客户已从不同城市订购。因此,我们有多个城市针对相同的customer_id。如果客户从多个城市订购了相同数量的订单,那么我想显示该城市与最近发生过次数的客户ID的比较。我尝试过像

这样的东西
private weak var lastPresentedController : UIViewController?

override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
    // WKWebView actions sheets workaround
    if presentedViewController != nil && lastPresentedController != presentedViewController  {
        lastPresentedController = presentedViewController;
        presentedViewController?.dismiss(animated: flag, completion: {
            completion?();
            self.lastPresentedController = nil;
        });

    } else if lastPresentedController == nil {
        super.dismiss(animated: flag, completion: completion);
    }
}

2 个答案:

答案 0 :(得分:0)

select customer_id,
       delivery_city,
       amount
from
(
select t.*,
       rank() over (partition by customer_id order by amount asc) as rank
from(
SELECT customer_id,
       delivery_city,
       COUNT(DISTINCT delivery_city) as amount
FROM analytics.f_order
GROUP BY customer_id,delivery_city
) t
)
where rank = 1

答案 1 :(得分:0)

WITH cte as (
    SELECT customer_id, 
           delivery_city, 
           COUNT(delivery_city) as city_count, 
           MAX(order_date) as last_order
    FROM analytics.f_order
    GROUP BY customer_id, delivery_city
), ranking as (
    SELECT *, row_number() over (partition by customer_id
                                 order by city_count DESC, last_order DESC) as rn
    FROM cte
)
SELECT *
FROM ranking 
WHERE rn = 1