我希望有人能够指出我在这里出错的地方,但我在过去的 30 分钟里一直在看这个,但没有得到任何结果。

我有一个填充数据的临时表,前端应用程序无法为我做任何逻辑,所以请原谅表中丑陋的 case 语句逻辑。

当我获得前 10 条记录时,用户对返回的结果集感到满意。他们现在决定将剩余的一组国家(所有行均不在前 10 名中)视为“其他”。

我曾尝试创建一组不在前 10 名中的国家,但它不起作用,我计划将此结果与前 10 名结果合并。

SELECT c.Country, count(*) AS 'Total_Number_of_customers', COALESCE(ili.new_customers,0) AS 'New_Customers', COALESCE(ilb.existing_first,0) AS 'Existing_First_Trans', COALESCE(ilc.existing_old,0) AS 'Existing_Prev_Trans'
FROM #customer_tmp c
LEFT JOIN (SELECT z.country, count(*) AS 'new_customers' FROM #customer_tmp z where z.customer_type='New_Customer' group by z.country)ili ON ili.country = c.country
LEFT JOIN (SELECT zy.country, count(*) AS 'existing_first' FROM #customer_tmp zy where zy.customer_type='Existing_Customer' AND zy.first_transaction=1 group by zy.country)ilb ON ilb.country = c.country
LEFT JOIN (SELECT zx.country, count(*) AS 'existing_old' FROM #customer_tmp zx where zx.customer_type='Existing_Customer' AND zx.first_transaction=0 group by zx.country)ilc ON ilc.country = c.country
GROUP BY c.country, ili.new_customers, ilb.existing_first, ilc.existing_old
ORDER BY 2 DESC

这是我用来从我的表中获取结果的 SQL。

作为引用,我的临时表中的每一行都包含一个客户 ID、他们的创建日期和他们的客户类型,这特定于我想要实现的目标。

希望这是一个简单的问题,我只是有点慢..

非常感谢Adv。

最佳答案

是的;除了,或者可能在您的查询中添加一个行号,然后选择:

SELECT * FROM (

SELECT c.Country, count(*) AS 'Total_Number_of_customers',
row_number() OVER (ORDER BY COUNT(*) DESC) AS 'r',
COALESCE(ili.new_customers,0) AS 'New_Customers', COALESCE(ilb.existing_first,0) AS 'Existing_First_Trans', COALESCE(ilc.existing_old,0) AS 'Existing_Prev_Trans'
FROM #customer_tmp c
LEFT JOIN (SELECT z.country, count(*) AS 'new_customers' FROM #customer_tmp z where z.customer_type='New_Customer' group by z.country)ili ON ili.country = c.country
LEFT JOIN (SELECT zy.country, count(*) AS 'existing_first' FROM #customer_tmp zy where zy.customer_type='Existing_Customer' AND zy.first_transaction=1 group by zy.country)ilb ON ilb.country = c.country
LEFT JOIN (SELECT zx.country, count(*) AS 'existing_old' FROM #customer_tmp zx where zx.customer_type='Existing_Customer' AND zx.first_transaction=0 group by zx.country)ilc ON ilc.country = c.country
GROUP BY c.country, ili.new_customers, ilb.existing_first, ilc.existing_old
ORDER BY 2 DESC

) sub_query WHERE sub_query.r >= 10

这可能更灵活,因为您可以运行一个查询,然后很容易地将结果分为“前十名”和“其余”。

(这相当于 bobs 的回答;我猜我们是在同一时间处理这个问题的!)

关于sql - 选择所有不在 Top 'n' 中的数据作为 'Other',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4511400/

10-13 03:29