SQL查询:添加百分比

时间:2017-11-02 23:57:02

标签: mysql

我有一个有效的查询,但除了我已经拥有的内容之外,我想为每个类别添加一个额外的列,免费,减少,支付和免费认证,百分比与学生总数相比。任何人都可以帮助我吗?

#include <iostream>
#include <conio.h>
#include <iomanip>

using namespace std;

const int   BASE_COST = 10;
const int   LOW_LIMIT = 20;
const int   MID_LIMIT = 40;
const int   HIGH_LIMIT = 60;
const double    LOW_CHECKS = .10;
const double    MIDLOW_CHECKS = .08;
const double    MIDHIGH_CHECKS = .06;
const double    HIGH_CHECKS = .04;

int main()
{
int numOfChecks;
double multiplierValue;
double totalFee;

cout << fixed << showpoint;
cout << setprecision(2);
cout << "Please enter the number of checks you used this month: ";
cin >> numOfChecks;

if(numOfChecks < 0)
{
    cout << "Number of checks can't be negative. Program ends.\n";
    exit(1);    //terminate the program with error code 1
}

//the following line runs only if the program did not terminate, so start over if-else
if(numOfChecks < LOW_LIMIT)
    multiplierValue = LOW_CHECKS;
else if(numOfChecks < MID_LIMIT)
    multiplierValue = MIDLOW_CHECKS;
else if(numOfChecks >= MID_LIMIT && numOfChecks < HIGH_LIMIT)
    multiplierValue = MIDHIGH_CHECKS;
else if (numOfChecks >= HIGH_LIMIT)
    multiplierValue = HIGH_CHECKS;  

totalFee = BASE_COST + numOfChecks * multiplierValue;

cout << "Your total for this month is $" << totalFee;

_getch();
return 0;
}

1 个答案:

答案 0 :(得分:0)

将现有查询视为派生表,将总计数交叉连接,然后计算百分比:

select
       d.*
     , d.Paid * 100.0 / cj.totcount as paid_pct

     ... more like that

from (
      select
              count(case when Lunchstatus = 'P'   then 1 else null end) as Paid
            , count(case when LunchStatus = 'R'   then 1 else null end) as Reduced
            , count(case when LunchStatus = 'F'   then 1 else null end) as Free
            , count(case when LunchStatus = 'fdc' then 1 else null end) as CertifiedFree
            , count(case when LunchStatus = 'P'   then 1 
                         when LunchStatus = 'fdc' then 1 
                         when LunchStatus = 'R'   then 1 
                         when LunchStatus = 'F'   then 1 
                         else null 
                         end) as Total
      from students
      where enroll_status = 0 
      and schoolid = %param1%
      ) d
CROSS JOIN (
       select count(*) as totcount
       from students
       where enroll_status = 0 
       and schoolid = %param1%
       ) cj