convert value to different level - javascript

I have an amount in postgres table which I can get through query select sum (price) from xyz I want to convert this value in different level like if I got 2000 it convert to
Price > 2000
1000 - 2000
500 - 1000
Price < 500
I want to show it in filter of the website... I am using (postgres, codeiginiter, javascript, jquery) can any of the language help me to create that format

finaly create thanx to all
select t1.row_number,t1.left,t2.right from
(SELECT row_number() over(),f2.* from(
SELECT generate_series(max(purchase_price::integer) , min(purchase_price::integer),-((max(purchase_price::integer))/5)) AS left FROM tbl_products) f2) t1
join
(SELECT row_number() over(),f.* from(
(SELECT generate_series(max(purchase_price::integer) , min(purchase_price::integer),-((max(purchase_price::integer))/5)) AS right FROM tbl_products offset 1)
union all
(select '0' as right)) f)t2
on t1.row_number =t2.row_number

i have this query SELECT generate_series(10000 , 2001,-((10000)/5)) AS left, generate_series(10000 , 2001,-((10000)/5)) AS right .... both right and left column shows same value... i just want right column start with second value and last row show 0
why are you doing this with SQL?
How about something like
var arr = [];
for(var i=10000; i >= 2001; )
arr.push([i, i -= 10000/5]);
console.log(arr);
.as-console-wrapper{top:0;max-height:100%!important}
... and last row show 0 contradicts your end-value of 2001. Your function call will generate the series [10000, 8000, 6000, 4000] not even 2000 is in there. So wich one is it? 0 or 2001?
Or this, if the previous code looks "hacky" to you:
for(var i=10000, j; i >= 2001; i=j){
var j = i - 10000/5;
arr.push([i, j]);
}

Related

Laravel9 - DB Query with one parent and 2 children not summing properly in selectraw

I have 3 tables : invoices, coletes, incasaris.
Invoices ID Coletes ID Invoice_id totaleuro Incasaris ID Invoice_id i_totaleuro
1 1 1 200 1 1 200
2 1 100 2 1 200
3 1 100
Basically, this query represents an invoice with the assigned parcels(coletes) and the receipts (incasaris). I want to sum coletes.totaleuro and incasaris.totaleuro foreach invoice.
My query looks like this:
$invoices = DB::table('invoices')
->leftJoin('coletes','coletes.invoice_id','=','invoices.id')
->leftJoin('incasaris','incasaris.i_plati_id','=','invoices.id')
->selectRaw('
sum(incasaris.i_totaleuro) as totalincasat,
sum(coletes.totaleuro) as total,
invoices.*
')
->orderBy('invoices.id')
->get();
The problem is that it should result in something as:
totalincasat : 400
total : 400
But it's returning
totalincasat: 1200
total: 400
I do believe the problem lies in the fact that the query simply multiplies the correct result of incasaris (400) with the number of coletes that belong to the invoice (3 in this case) .
Any help would be appreciated I've been searching for a solution for a while on the web but I don't seem to find any similar post.
Thank you
To return the total, you either need to sum in a subquery or group the result.
Using a subquery would be something like:
DB::table('invoices')
->selectRaw('(SELECT SUM(totaleuro) FROM coletes WHERE coletes.invoice_id = invoices.id')
// and so on to add the other cols
Grouping would be something like:
DB::table('invoices')
->leftJoin('coletes','coletes.invoice_id','=','invoices.id')
->sum('coletes.totaleuro')
->groupBy('invoices.id')

How to update sequentially in order in different rows and insert a new one?

I don't really know how to approach this, thing is, I'm developing a web application and in a section I need to assign projects to other developers, every assignment/project will have a priority of how important it is. Priority 1 is the highest (more important), and priority 5 is lowest (less important).
What the system has to do is, when I add a new priority 1 (or any other priority), if there are other priorities and a priority 1, move the others down (P1 = P2, P2 = P3, P3 = P4) and add the new one as P1.
I made a little piece of code (making everything manually that will only work once but is just for you to see what I want)
//PHP CODE
//prioridad = "P1" from a button
$prioridad = validacion::limpiar_cadena($_POST['prioridad']);
$estado = "";
$pes = array();
//I get all the priorities from my user and save them in this array
//Saving an array of the user's priorities
while ($row = $resultado->fetch_assoc()){
$pes[] = $row["prioridad"];
}
//Replace current priorities with their new one (just once)
if (in_array($prioridad, $pes)){
if (in_array("P5", $pes)){
$estado = "lleno";
}
//Make priority 4 = priority 5 and same for all
//This user just had the first 3 priorities,so this one did nothing but the others updated succesfully just for this example
if (in_array("P4", $pes)){
$upd= $conexion->prepare("UPDATE asignarproyectousuario SET prioridad = 'P5' WHERE idUsuario = 1 AND idProyecto = 32");
$upd->execute();
}
if (in_array("P3", $pes)){
$upd= $conexion->prepare("UPDATE asignarproyectousuario SET prioridad = 'P4' WHERE idUsuario = 1 AND idProyecto = 2");
$upd->execute();
}
if (in_array("P2", $pes)){
$upd = $conexion->prepare("UPDATE asignarproyectousuario SET prioridad = 'P3' WHERE idUsuario = 1 AND idProyecto = 1");
$upd->execute();
}
if (in_array("P1", $pes)){
$upd= $conexion->prepare("UPDATE asignarproyectousuario SET prioridad = 'P2' WHERE idUsuario = 1 AND idProyecto = 3");
$upd->execute();
}
$insert = $conexion->prepare("INSERT asignarproyectousuario(idProyecto, idUsuario, prioridad) VALUES(4, 1, ?)");
$insert->bind_param("s", $prioridad);
$insert->execute();
}
I tried using arrays and adding a value of one to the current priority but I don't know how to make it work, separate the array and assign every value to a row in the database.
I also found queues that make exactly that "movement" of adding one priority and move the others in order, but I haven't found much documentation about it.
This is the example I saw:
$queue = new SplQueue();
$queue->enqueue('prioridad1');
$queue->enqueue('Prioridad2');
$queue->enqueue('Prioridad3');
$queue->unshift('prioridad1');
$queue->rewind(); // always rewind the queue/stack, so PHP can start from the beginning.
while($queue->valid()){
echo $queue->current()."\n"; // Show the first one
$queue->next(); // move the cursor to the next element
}
echo "\n"."\n"."\n";
var_dump($queue);
If you could give me an idea of how to do it or a different example would be very helpful.
Thanks in advance and if my english is not good enough I can try to explain it better.
technique is simple >
you need to know how JSON works
add an Extra column (text) in mysql Table >
store JSON array in that column Like >
[{"TaskName":"XYX","AssignDate":"AnyDate","Priority":"High","PriorityCount":"50"}]
add extra array in JSON / Update array whenever require
itarate the array that finds ("Priority":"High" AND "PriorityCount": "" // highest)
this might help > Getting max value(s) in JSON array

Optimize result page to query number of result first

Here is my code. But I have some problem about loading time for result more than 1000 rows.
How can I change code to check number of query result for create paginate first. Then, get result only that paginate page?
function showResult(req, res){
var n = req.query.query;
mysql_conn.query('SELECT query_text FROM catalogsearch_query WHERE query_text LIKE "%' + n + '%" ORDER BY popularity DESC LIMIT 0 , 10', function (error, rows) {
mysql_crawl.query('SELECT prod_name, full_price, discount_price, quantity, fulltext_id,prod_link, images, prod_desc, status, web_name,web_logo FROM `catalogsearch_fulltext` WHERE MATCH(data_index) AGAINST("'+n+'") ', function(error, product_data) {
var totalItems = product_data.length, itemts=product_data;
//set default variables
var totalResult = totalItems,
pageSize = 10,
pageCount = Math.floor(totalResult / pageSize)
currentPage = 1
//set current page if specifed as get variable (eg: /?page=2)
if (typeof req.query.page !== 'undefined') {
currentPage = +req.query.page;
}
//render index.ejs view file
res.render('result.html', {result: n,
related: rows.map(row => row.query_text),
page_num: p,
product_data: product_data,
totalItems: totalItems,
pageSize: pageSize,
pageCount: pageCount,
currentPage: currentPage})
});
});
}
first you get the total rows of the result
SELECT COUNT(*) FROM table WHERE 1 = 1;
second is the query to get the rows result but limit by ex. 10 and offset starts at zero first
SELECT * FROM table WHERE 1 = 1 LIMIT 10, 0;
it means the result will start at 0 then for the next page you should add 10 for your offset
SELECT * FROM table WHERE 1 = 1 LIMIT 10, 10;
so it starts at 10 up to 20
So actually two sides: client side and server side.
Client side, using angularjs, please evaluate to use the angular ui pagination directive:
https://github.com/angular-ui/bootstrap/tree/master/src/pagination
Here a link to a stackoverflow post where there is a working example of it:
How to do paging in AngularJS?
About your server side, you could provide a way to make your query dynamic, retrieving just results in the range you pass on it. So something like that:
'SELECT query_text FROM catalogsearch_query WHERE query_text LIKE "%' + n + '%" ORDER BY popularity DESC LIMIT %, %'
where you pass your limit parameters from the client according to the pagination.
So before to load a new page, you call the query with the right LIMIT parameters

Javascript Array 2 keys return one value

this is really hurting my brain so I hope somebody can help.
I have some data from a spreadsheet that has 2 axis'
AGE 50 51 52
£7 £1,497 £1,479 £1,458
£8 £1,746 £1,725 £1,701
£9 £1,996 £1,972 £1,944
the user will input there age into a input box on the page, and click next, i save this into a variable
var age = 50;
the user is then present with another input box and can input a value from 0 - 100
i then save this into another variable
var ammount = 10;
with the two values i need to search the array for the corosponding values to return the answer.
the data i have is currently in a spread sheet, i need to take this data from the spreadsheet put this into an array in java script.
with the two values i need to find the relevant answer.
Try somethink like:
var row1 = {
"50" : "£1,497",
"51" : "£1,479"
// etc
}
var dictionary = {
"£7": row1
// etc
}
Next, call dictionary["£7"]["50"]

Generating a price per item in an html table using a javascript

I have a javascript that is generating a table for me. The elements in the table are gathered in an array of arrays called sep. Sep contains 1152 sub arrays that are of the form:
Sep[0] //["316SS", "K", "-100 to 225°C", "Brass", "1/8", "4'", "4'", "8", "Ungrounded"]
So basically there are 1152 rows, each of which defines a products with 9 parameters. I want to make a for-loop that will create a price for each of the configurations. This is what I have so far:
//PART 1-------------WORKS FINE-----------------------------------
var eopartprice2 = []; //matrix that I want to contain my prices
for (var i = 0; i < sep.length; i++) {
strnum1 = sep[i][5]; //parameter 5 is a length of material
len1 = Number(strnum1.substr(0, strnum1.length - 1));
strnum2 = sep[i][6]; //parameter 6 is another length of material
len2 = Number(strnum2.substr(0, strnum2.length - 1));
strnum3 = sep[i][7]; //parameter 7 is the number of units required
condnum = Number(strnum3.substr(0, strnum3.length));
feetOfMat = len1*len2*condnum; //The product of these is the total feet of req material
//PART 2------------PFCost always = 0.87--------------------------
//Next i need to identify the cost of the material (to multiply by the total feet)
var costOfMat = [0.87, 0.87, 1.77, 0.55] //different costs of the 4 materials
if (sep[i][0] = "304SS") {
var PFCost = costOfMat[0]; //304SS costs 0.87/foot
} else if (sep[i][0] = "316SS") {
var PFCost = costOfMat[1]; //316SS costs 0.87/foot
} else if (sep[i][0] = "Inconel") {
var PFCost = costOfMat[2]; //Inconel costs 1.77/foot
} else if (sep[i][0] = "High Temp. Glass") {
var PFCost = costOfMat[3]; //High Temp. Glass costs 0.55/foot
}
baseMatCost[i] = PFCost*feetOfMat; //I'd like to generate a matrix that
//contains all of the base prices (1 for each row)
//PART 3---------------fitcost always = 36------------------------
//Trying to identify the cost of brass vs. stainless fittings
if (sep[i][3] = "Brass") {
fitcost = 36;
} else if (sep[i][3] = "Stainless Steel") {
fitcost = 37;
}
}
My Problem so far is that I want the prices to be defined based off of whether or not the if statements are satisfied but in both cases (fitcost and PFCost) the values are simply the ones defined in the first if statement.
Lastly I'd like to generate my final price in the eopartprice2 matrix based off adding up the materials generated above + some cost of labor multiplied by some margin.
Also I'm concerned with the speed of how quickly this runs as it will be a live table in my website, and every time I add more to this I feel like it's taking longer and longer to generate. Here's a link to my w3 that I'm working in.
Please, any help would be greatly appreciated :)
In your if statement conditions, you're using a single equals sign. This is an assignment operator, not a comparison operator!
So, an if statement such as if (sep[i][0] = "304SS") is actually assigning the value "304SS"; it is not comparing the value "304SS" to sep[i][0].
To correctly compare the values, you'll want to change the single equals sign to a double equals:
if (sep[i][0] == "304SS").
Note: == will convert types if necessary before comparing. For example: ".87" == 0.87 returns true.

Categories

Resources