Heim  >  Fragen und Antworten  >  Hauptteil

Berechnungsergebnisse in SQL mit 2 Dezimalstellen anzeigen

Ich habe eine einfache Abfrage geschrieben, um den Prozentsatz von zwei Spalten zu ermitteln, aber ich möchte, dass die Ergebnisse in der Spalte mit nur zwei Dezimalstellen stehen. Folgendes habe ich geschrieben, aber ich erhalte eine Fehlermeldung, die ich scheinbar nicht beheben kann.

SELECT 
    Small_Bags,
    Total_Bags,
    (Small_Bags / Total_Bags) * 100 AS Small_Bags_Percent
    (Select CAST (Small_Bags_Percent AS DECIMAL (10,2)))
FROM Table_Bags
WHERE Total_Bags <>0

P粉055726146P粉055726146182 Tage vor356

Antworte allen(1)Ich werde antworten

  • P粉653045807

    P粉6530458072024-04-03 12:46:35

    您不能在同一查询中使用列别名。你可以做到这一点。

    select Small_Bags
        , Total_Bags
        , (Small_Bags / Total_Bags) * 100 AS Small_Bags_Percent
        , cast(((Small_Bags / Total_Bags) * 100) as decimal(10,2))
    from Table_Bags
    where Total_Bags > 0

    或者使用子查询

    select t1.Small_Bags, t1.Total_Bags, t1.Small_Bags_Percent
        , cast(t1.Small_Bags_Percent as decimal(10,2))
    from 
        (select Small_Bags
            , Total_Bags
            , (Small_Bags / Total_Bags) * 100 AS Small_Bags_Percent
            , cast(((Small_Bags / Total_Bags) * 100) as decimal(10,2))
        from Table_Bags
        where Total_Bags > 0) t1

    Antwort
    0
  • StornierenAntwort