I'm trying to achieve this query in CubeJS which does a LEFT OUTER JOIN with itself.
SELECT COUNT(DISTINCT EC."accId")
FROM public."orders" EC
LEFT OUTER JOIN public."orders" NC
ON NC."accId" = EC."accId"
AND NC."isFirstOutletTransaction" = true
AND NC."occurredAt" > '2020-02-01'
AND NC."occurredAt" < '2020-03-01'
WHERE EC."occurredAt" > '2020-02-01'
AND EC."occurredAt" < '2020-03-01'
AND EC."isFirstOutletTransaction"=false
AND NC."accId" is null;
I'm stuck on how to express this in the CubeJS schema. Would appreciate the help. Thanks
You can create one cube called e.g. "FirstOutletTransatction" with the appropriate condition:
sql: 'select * from public."orders" NC where NC."isFirstOutletTransaction" = true'
then define the other cube e.g. "NonFirstOutletTransatction" like:
sql: 'select * from public."orders" NC where NC."isFirstOutletTransaction" = false'
Define the relation of the two cubes in their joins and add "occurredAt" either as time dimension or in the query as a condition.
Related
I want to update ta.nmbr and ta.totl to an existing indctr. How do I do it? is it possible to join?
This is the SELECT query.
$sql = "SELECT ind.indctr_code, ind.indctr_name, ctr_ind.ctr_indctr_id, ta.actl_trgt, ta.nmbr, ta.totl
FROM indctr AS ind
LEFT JOIN ctr_indctr
AS ctr_ind ON ind.indctr_code = ctr_ind.indctr_code
LEFT JOIN actl_trgt AS ta
ON ctr_ind.ctr_indctr_id = ta.ctr_indctr_id
LEFT JOIN qtr
ON ta.qtr_code = qtr.qtr_code";
This is the ralationship of the entities.
I was doing an inline editing table for this where the indctr_code and the indctr_name are already there. and the data for ta.nmbr & ta.totl will be editable in the table.
A plain UPDATE:
UPDATE actl_trgt
SET nmbr = 90
, totl = 100
WHERE actl_trgt = 1;
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
In the following code I am joining two table and searching for a proper name:
const homesWithUsers = knex('homes')
.join('users', 'homes.id', 'users.home_id')
.whereRaw(
`LOWER("homes.name") LIKE ?`,
'%' + payload.home_name.toLowerCase() + '%'
)
//Stringified
select * from "homes" inner join "users" on "homes"."id" = "users"."home_id" where LOWER("homes.name") LIKE '%george%'
I need to use whereRaw because the database column and the search term are proper names where capitalization is uncertain. (Storing an extra column of the proper names represented in all uppercase is not an option.) However, this query fails with: error: column "homes.name" does not exist. If I remove homes. the query is ambiguous (error: column reference "name" is ambiguous) because both the user and home tables have the columns name.
If I do a simple where statement the query is successful
const homesWithUsers = knex('funeral_homes')
.join('users', 'homes.id', 'users.home_id')
.where({ 'homes.name': payload.home_name })
.select('*');
The only problem is that this will fail with the payload values I expect to field from users interacting with the database.
Any suggestions for how to successfully perform a whereRaw on a joined table?
You need to use identifier replacement syntax ?? when passing column identifiers to raw, which needs to be quotet properly. Like this:
const homesWithUsers = knex('homes')
.join('users', 'homes.id', 'users.home_id')
.whereRaw(
`LOWER(??) LIKE ?`, ["homes.name", '%' + payload.home_name.toLowerCase() + '%']
)
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]);
}
hi i am new to codenighter frame work soome one can help me that how can i convert this join query to codenighter frame work and also told me that where i have to kept the join query i mean in model or controller..?
and how can i fetch the result of this query ..?
i want to pass the class_id as parameter..?
my query is here ..
SELECT e.roll,s.name,p.title,i.amount,i.amount_paid,i.status,i.creation_timestamp
FROM `payment` p
INNER JOIN student s ON s.student_id=p.student_id
INNER JOIN enroll e ON e.student_id=p.student_id
INNER JOIN invoice i ON i.student_id=p.student_id AND e.class_id=6 AND e.year="2016-2017"
You need to keep this SQL query in your model and then pass the result to controller. You can pass the result set to controller from model and can use it from there. If you wan to pass it to view then you need to pass its data variable into view variable.
it should be like this,
In MODEL File:
function get_data(){
$this->db->select('enroll.roll,student.name,payment.title,invoice.amount,invoice.amount_paid,invoice.status,invoice.creation_timestamp');
$this->db->from('payment');
$this->db->join('student', 'student.student_id = payment.student_id', 'inner');
$this->db->join('enroll', 'enroll.student_id = payment.student_id', 'inner');
$this->db->join('invoice', 'invoice.student_id = payment.student_id', 'inner');
$this->db->where(array('enroll.class_id'=>6,'enroll.year'=>'2016-2017'));
$query = $this->db->get();
if($query->num_rows()>0){
return $query->result_array();
}
}
In CONTROLLER you can call this model function like this:
$data['Data'] = $this->student_model->load_countries();
$this->load->view('student_data',$data);
This is as per CodeIgniter active record framework. Hope this will help you.
you can use query method to write your own query .
in query method you can use joins easily
for example
Your Model
class Model_name extends CI_Model {
function __construct()
{
parent::__construct();
}
public function get_record(){
$data = $this->db->query('
SELECT e.roll,s.name,p.title,i.amount,i.amount_paid,i.status,i.creation_timestamp
FROM `payment` p
INNER JOIN student s ON s.student_id=p.student_id
INNER JOIN enroll e ON e.student_id=p.student_id
INNER JOIN invoice i ON i.student_id=p.student_id AND e.class_id=6 AND e.year="2016-2017"
');
if($data->num_rows()>0){
return $data;
}
}
}
$this->db->join() is helper funtion to perform join query
Permits you to write the JOIN portion of your query:
$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
// Produces:
// SELECT * FROM blogs JOIN comments ON comments.id = blogs.id
Multiple function calls can be made if you need several joins in one query.
If you need a specific type of JOIN you can specify it via the third parameter of the function. Options are: left, right, outer, inner, left outer, and right outer.
$this->db->join('comments', 'comments.id = blogs.id', 'left');
// Produces: LEFT JOIN comments ON comments.id = blogs.id
You can directly write query in the query() function too.
$query = $this->db->query('SELECT e.roll,s.name,p.title,i.amount,i.amount_paid,i.status,i.creation_timestamp
FROM `payment` p
INNER JOIN student s ON s.student_id=p.student_id
INNER JOIN enroll e ON e.student_id=p.student_id
INNER JOIN invoice i ON i.student_id=p.student_id AND e.class_id=6 AND e.year="2016-2017"');
References: CodeIgniter Docmentation
Refer:-https://www.codeigniter.com/userguide3/database/query_builder.html
You can also use below style:-
In MODEL File:
function get_data(){
$this->db->where(array('enroll.class_id'=>6,'enroll.year'=>'2016-2017'));
$this->db- >select('enroll.roll,student.name,payment.title,invoice.amount,invoice.amount_paid,invoice.status,invoice.creation_timestamp');
$query = $this->db->from('payment')->join('student', 'student.student_id = payment.student_id', 'inner')->join('enroll', 'enroll.student_id = payment.student_id', 'inner')->join('invoice', 'invoice.student_id = payment.student_id', 'inner')->get();
if($query->num_rows()>0){
return $query->result_array(); //You can also use result(); provide object array
}
}
In CONTROLLER you can call this model function like this:
$data['Data'] = $this->student_model->load_countries();
$this->load->view('student_data',$data);
In view you can get this with $data variable