How to use a calculated column to calculate another column in codeigniter - sql

i hope you can help me with this simple question.
i try to use this nested query in codeigniter.
Select
ColumnA,
ColumnB,
calccolumn1,
calccolumn1 / ColumnC as calccolumn2
From (
Select
ColumnA,
ColumnB,
ColumnC,
ColumnA + ColumnB As calccolumn1
from testtable
);
how to convert this to codeigniter?
i know the inner SELECT should look a bit like this:
$this->db->select('ColumnA,ColumnB,ColumnC,ColumnA + ColumnB As calccolumn1');
$this->db->from('testtable');
$subquery = $this->db->get();
...
but then how do i have to proceed?

Thanks for you fast reply!
The query is working fine now! but i cant seem to find how to add the WHERE clause with my variable ($data) from the method which i wanted to add now.
normally i use
$this->db->where('Username', $data);
but since the where clause is now in the query, i didnt find a way yet to add it inside the query.

When it comes to more complicated queries I usually just do this:
$variable = 'x';
$query = $this->db->query("
SELECT...
FROM...
WHERE some_column = '$variable'
");
return $query->result_array();

Related

Laravel raw query: total with select inside count

I'm building a SQL query (Postgres is it matters), that will return me the list of articles with all the fields and with total number of references.
$a = Articles::select(DB::raw('
*,
count(
select * from "references"
where exists (select * from "users" where "users"."reference_id" = "references"."id"
and "article_id" = ?????
) as total'
))->where('created_at', '<', $date)->get();
I simplified it a little bit; there more 'exists' conditions inside the count(); there is also more ->where() rules that are dynamic and hard to rewrite in raw SQL. My main misunderstanding is how to put the corresponding article_id instead of ?????. Could someone give me a hint.
Try this its about binding parameter to Raw query.
https://laracasts.com/discuss/channels/laravel/how-to-bind-parameters-to-a-raw-query?page=1
You may pass in the parameters to be bound to the raw select using a PHP array:
$a = Articles::select(DB::raw('
*,
count(
select * from references r
where exists (select 1 from users u
where u.reference_id = r.id and article_id = ?)
) as total', ['some id here']))
->where('created_at', '<', $date)
->get();
There may be a better way to write your query in Postgres. If you can add some sample data, maybe more can be said about that.

Compare varchar values postgresql

I'm new in the db world and I'm trying to do my first queries.
I have two tables and I need compare the value of the columnA, in the first table, with the value of the columnB in the second table.
I would like to know what values in the columnA are in the columnB. Both columns are varchar type.
I've tried this two queries:
select *
from tableA
join tableB
on (tableA.columnA = tableB.columnB);
select *
from tableA
where columnA in (select columnB
from tableB);
But both get me back empty table.
I checked the values manually, and there are many equal values.
Maybe the = isn't the right operator with the string values?
This is a simple example of what I would do, with the expected result at the end.
TableA
columnA descriptionA
EF8236PA xyx
EF7843DV dgfd
EF6535MD dshr
EF3274LK hghg
EF6940BN fdtsg
EF3405TJ dsbfbs
TableB
columnB
EF3405TJ
EF6940BN
EF6535MD
Result:
EF3405TJ
EF6940BN
EF6535MD
Both of your queries are looking fine. you can add few more conditions in the where clause that will make it work.
Example:
select *
from tableA
join tableB
on (upper(trim(tableA.columnA)) = upper(trim(tableB.columnB)));
Trim will cut down extra spaces and upper will make the search case insensitive.
Hope this will help.
I would like to know what values in the columnA are in the columnB.
Strictly speaking, this query is a correct (and fast) query to implement what you ask:
SELECT DISTINCT columnA
FROM tableA a
WHERE EXISTS (SELECT 1 FROM tableB WHERE columnB = a.columnA);
The manual about EXISTS.
But neither of your queries should return empty sets. There may be whitespace or other invisible characters fooling you. Test with:
SELECT * FROM tableA WHERE columnA = 'EF6940BN';
SELECT * FROM tableB WHERE columnB = 'EF6940BN';
I tried all your suggestions, but no one works.
So I tried run the code on another postgre and the same code that I wrote above works.
I don't understand why, the postgre's versions are the same

Adding together two column sums in SQL Server2005

Ive come across a problem when trying to add together two column sums.
Ive created a view with all the correct data in but when i try to execute a query like:
Select ID, Sum(ColumnA),
Sum(ColumnB)
Sum(ColumnA) + Sum(ColumnB) AS ColumnC
From View1
Group by ID
The ColumnC figure is only correct when there is data in both columns, if there is only data in ColumnB then it displays that but if there is only data in ColumnA then it doesnt.
Sometime when there isnt any data in ColumnA or B it will be NULL, so maybe this is the problem.
Hope there is a way around this.
Cheers
Try using ISNULL to substitute zeros for NULLs:
Select ID, Sum(ColumnA),
Sum(ColumnB)
ISNULL(Sum(ColumnA),0) + ISNULL(Sum(ColumnB),0) AS ColumnC
From View1
Group by ID
Adding something to a null value gives a null result, the null is not converted to zero. You have to do that conversion explicitly:
Select ID, Sum(ColumnA),
Sum(ColumnB)
isnull(Sum(ColumnA), 0) + isnull(Sum(ColumnB), 0) AS ColumnC
From View1
Group by ID
You can use COALESCE to replace NULL inputs to the calculation with zero as below.
COALESCE(Sum(ColumnA),0) + COALESCE(Sum(ColumnB),0) + AS ColumnC
Or ISNULL as in the other 2 answers. Doesn't matter which if portability is not a concern.

An regex to extract SQL where clause

First, I confess I'm not realy experimented with regular expressions. I know how use it but when I want to build one, it's something else... I'm going to document me.
I want to extract the WHERE clause in a SQL query. My goal is to be able to add an condition, like this:
SELECT * FROM myTbl WHERE columnA = 'B' AND columnB = 'C' ORDER BY columnX GROUP BY columnZ LIMIT 5
TO :
SELECT * FROM myTbl WHERE columnC = 'D' AND (columnA = 'B' AND columnB = 'C') ORDER BY columnX GROUP BY columnZ LIMIT 5
I tried some expression but I'm so void...
(where (.*)(?<=order by))
I wanted to get all between 'where' and ('order by' or 'limit' or 'group by')...
Anyone have an advice for me ? I have done some search and I don't find anything like this. I found SQL Parser but these engines are too big compared to the task I want to complete.
Thank you.
Since the WHERE clause can be quite complex (including subqueries which may include an ORDER BY in some cases, for instance when used with FOR XML), so you will not be able to really find an always reliably working solution with a regex.
A better solution would be to use a proper SQL parser which generates an AST, and then you can just extract the WHERE clause from that. For T-SQL, you could use the parser from the bsn ModuleStore project (LGPL license). Modifying the AST is easy and you can re-script the statement afterwards.
You're using lookbehind (?<=) whereas you need lookahead (?=) assertion.
There's more on that.
This might get you going:
declare
sql_stmt varchar2(4000) := q'!SELECT * FROM myTbl WHERE columnA = 'B' AND columnB = 'C' ORDER BY columnX GROUP BY columnZ LIMIT 5!';
where_stmt varchar2(4000) ;
begin
where_stmt := regexp_replace(sql_stmt, '.*(WHERE.*?)ORDER BY.*', '\1');
dbms_output.put_line(where_stmt);
end;
/
The scriplet above will output WHERE columnA = 'B' AND columnB = 'C'.

Select query in SQL

I have a very curious question.
We have query to select records from table based on some condition. In general the syntax for the query is as below
SELECT * FROM TABLENAME WHERE COLUMNNAME='VALUE';
Now the question is that will this query will work if we interchange the position of COLUMNNAME and 'VALUE'.
Yes, it will. =)
Why did you not just try?
Yes. The following will work:
SELECT * FROM TABLENAME WHERE 'VALUE' = COLUMNNAME;
In fact, in Oracle at least, you can do some twisted but somewhat useful things like:
select *
from tablename
where 'VALUE' in (field1, field2, field3)
You mean
SELECT * FROM TABLENAME WHERE 'VALUE' = COLUMNNAME;
I tested it, it works on MSSQL Servver 2008
SELECT * FROM TABLENAME WHERE 'VALUE' = COLUMNNAME;
if write something like this.. it'll work for sure..