使用SQL按价格访问前10名

时间:2015-07-21 14:28:55

标签: sql ms-access

select top 10 Account_Name, Indemnity_Paid/Claim_Count as Indemnity_Cost
from Final_For_DB
Group by Account_Name
order by Indemnity_Cost desc;

我的FINALFOR_DB中有三列,它们是:

  • ACCOUNT_NAME
  • indemnity_paid
  • claim_count
  • 我想编写一个查询,它将为我提供按account_name分组的前10个值。赔偿费用的计算方法是将indemnity_paid除以claim_count,以获得确切的费用。

    任何人都可以帮我吗?

    修改

    现在我有了这个:

    SELECT TOP 10 [FINAL_FOR_DB].[Indemnity_Paid]/[FINAL_FOR_DB].[Claim_Count] AS Indemnity_Cost, final_for_db.Claimant_Name, final_for_db.Account_Name, final_for_db.Claim_ID, final_for_db.File_Date, final_for_db.Resolution_Date, final_for_db.Claim_Status, final_for_db.State_Filed, final_for_db.Expense_Amount
        FROM final_for_db
        GROUP BY [FINAL_FOR_DB].[Indemnity_Paid]/[FINAL_FOR_DB].[Claim_Count], final_for_db.Claimant_Name, final_for_db.Account_Name, final_for_db.Claim_ID, final_for_db.File_Date, final_for_db.Resolution_Date, final_for_db.Claim_Status, final_for_db.State_Filed, final_for_db.Expense_Amount
        HAVING (((final_for_db.Account_Name)="Exxon"))
        ORDER BY [FINAL_FOR_DB].[Indemnity_Paid]/[FINAL_FOR_DB].[Claim_Count] DESC;
    

    我想知道在一个查询中是否可以为每个帐户排名前10位。在这一个中,我不得不使用Exxon作为帐户名称的条件。

    2 个答案:

    答案 0 :(得分:0)

    您没有明确说明,但我认为上述查询没有达到您想要的效果。

    这可能是因为select的计算无法在order bywhere等条款中重复使用。

    您需要在后续条款中再次明确地执行计算,无论何时需要。

    答案 1 :(得分:0)

    我不确定它在性能方面是否更快(从未测试过):我会使用:

    select T1.* from 
    (Select Top 10 Account_Name, Indemnity_Paid/Claim_Count as Indemnity_Cost
    From Final_For_DB
    WHERE account_name = "account_name"
    ) AS T1
    Order By T1.Indemnity_Cost DESC;
    

    另外:Access SQL需要聚合函数,用于组函数中涉及的所有字段。我会写这样的SQL:

    select T1.* from 
    (Select Top 10 Account_Name, sum(Indemnity_Paid)/sum(Claim_Count) as Indemnity_Cost
    From Final_For_DB
    WHERE account_name = "condition" 
    Group By Account_Name) AS T1
    Order By T1.Indemnity_Cost DESC;
    

    由于您正在通过account_name进行摸索,因此您还应该将“indemnity_paid”和&所有匹配行中的claim_count字段,除非该字段已经是表/查询中的计算字段。在这种情况下,您可以简单地使用第一种方法,但也可以按account_name排序