gpt4 book ai didi

sql - 选择所有不在Top 'n'中的数据为 'Other'

转载 作者:行者123 更新时间:2023-12-01 23:11:28 24 4
gpt4 key购买 nike

我希望有人能指出我在哪里出错了,但我在过去的 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.

最佳答案

使用 EXCEPT operator in SQL Server :

SELECT <fields>
FROM <table>
WHERE <conditons>
EXCEPT
<Query you want excluded>

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com