is there a way to query same db field with two different where clause in the same query? - couchbase

I have a condition that I need to query Couchbase database field with two different where clauses in the same query.
for example:
for 'sales' field in a database entity, I want to have one query to get the sales in a single hour and whole day
output example:
`{`
`hourly_sales = 500`
`total_day_sales = 5000
`}`
I know that I can use 2 different queries, but requirement is to use one query for both

You can achieve that using case when statement. For example -
SELECT SUM(CASE WHEN `TIME` BETWEEN "13:00:00" AND "14:00:00" THEN `SALES`) AS HOURLY_SALES,
SUM(CASE WHEN `TIME` BETWEEN "00:00:00" AND "23:59:59" THEN `SALES`) AS TOTAL_DAY_SALES
FROM `BUCKET_NAME`
Make use of the time format according to your need.

Related

How to Create Two Columns from One Column in SQL Based on a IF argument in Another Column

I have a table that has 3 columns. Value, condition and day. I would like to SELECT two columns from column Value. One which is average value of t.value grouped by t.condition 1 and another one which is an average value of t.value grouped by t.condition 2. I would then like to group them all by day and condition.
Result should look like this table.
I have tried case when, if and CTEs. However, they all failed. The if statement work for fulfilling one condition but seeing that condition is binary, the if function i tried did not work. I have considered creating two tables and then joining on day. That would work I would assume. Would there be an easier way of doing this?
Thank you!
You can use conditional aggregation:
select day,
max(case when condition = 1 then value end) as value_1,
max(case when condition = 2 then value end) as value_2
from t
group by day;

Table Manipulation in SQL

The table I have right now is this:
Is there a way in MySQL to manipulate and spread the table to:
This is called records to columns conversion or pivot.
The general query structure is, done with a GROUP BY , CASE END and some aggregate function like MAX, MIN or SUM. In MySQL/MariaDB or anny database system which does not have a PIVOT() kind of function
Where MAX() and MIN() can pivot every datatype, SUM() is only suitable for numeric datatypes.
SELECT
Name
, SUM(CASE WHEN Cycle = 'weekly' THEN 1 ELSE 0 END) AS weekly
..
..
FROM
t
GROUP BY
Name
Note because SQL tables when stored and selections off SQL tables are by SQL definition orderless so the result off this query is nondeterministic (random), there wasn't anny column in your data example which could be used to make a deterministic (fixed) order by

Select records by month in where clause

My query to get data by month
$this->db->select('vehicle_make_and_model');
$this->db->join('tukai_drivers','tukai_drivers.driver_id=reqn_challans.dc_driver_id','left');
$this->db->where('dc_challan_date','MONTH(2)');
$this->db->order_by('dc_challan_id','desc');
$result=$this->db->get('reqn_challans')->result();
I am trying it via codeignitor like this
$this->db->where('dc_challan_date','MONTH(2)');
It did not work? What is wrong
Storing date like this
http://awesomescreenshot.com/0424q72ne5
You need to update your where condition from
$this->db->where('dc_challan_date','MONTH(2)');
to
$this->db->where('MONTH(dc_challan_date)','2');
The actual function is like MONTH(date) so here you have MONTH(dc_challan_date) which is your column name
In SQL databases you should NOT apply functions to data to suit the where clause so that you maximize the benefit of indexes (i.e. get better performance). For example, instead of using MONTH(dc_challan_date) you can achieve getting a month of data using the >= with < such as the following SQL:
select * from table
where dc_challan_date >= '2015-02-01'
and dc_challan_date < '2015-03-01'
The database optimizer can use an index on column dc_challan_date in that query. The example uses "sargable predicates".

CONCAT in WHERE clause of SELECT statement in mysql

M2014 is a text field in the DB table.
This statement works correctly (returns count = 368)
SELECT count(*) FROM arealist WHERE M2014 = 'Yes'
However, I having problems with this statement (returns count = 0) All I have changed
is the concat
SELECT count(*) FROM arealist WHERE concat('M','2014') = 'Yes'
What could be the cause and solution?
You are comparing two strings in the second SELECT statement. The second statement is appending two strings 'M' and '2014' which results in the query comparing 'M2014' to 'Yes' two strings, not the value of the column. Making a statement like this:
SELECT COUNT(*)
FROM AreaList
WHERE M2014 = CONCAT('Y','es')
That statement would return 368 rows. What are you ultimately trying to do with this statement?
You can't generate a dynamic column name for the where clause in MySQL. There are a number of Stack Overflow articles to that effect. Normally, I would arrange my data so that there was some sort of date or timestamp associated with the row, rather than using date specific columns. (I'm assuming M2014 has something to do with the year 2014). When arranged this way you can select what you need based on whatever date requirements you have.
That said, if your data model is fixed, then you're best bet is probably to use another language, C#, python, whatever, to create the column names you need dynamically and then send the entire query to MySQL. Alternatively, you could write a series of SQL statements, one for date column you're interested in.
The following query in google turned up a number of relevant results: https://www.google.com/search?client=opera&q=dynamic+column+names+in+sql&sourceid=opera&ie=utf-8&oe=utf-8&channel=suggest&safe=active#channel=suggest&q=dynamic+column+names+in+mysql+where+clause&safe=active
you can do it in php like that
$year = 2014;
SELECT count(*) FROM arealist
WHERE M$year = 'Yes'

How can i optimize SUM() mysql Query

I have a mysql SUM query that runs on more than 0.6 million records.
what i am currently doing is like this
SELECT SUM (payment)
FROM payment_table
WHERE
payment_date BETWEEN ... AND ...
AND
payment_status = 'paid'
I changed the query to this format to reduce the recordset but it is still taking almost same time.
SELECT SUM(Payments)
FROM (
SELECT payment AS Payments FROM payment_table WHERE
payment_date BETWEEN DATE_FORMAT(NOW(), '2012-2-01') AND DATE_FORMAT(LAST_DAY(DATE_FORMAT(NOW(), '2012-2-01')), '%Y-%m-%d')
AND
payment_status = 'paid'
) AS tmp_table
Is their any way to optimize this sum query.
EDIT:
This is the result when query is run with EXPLAIN
insert into ` (id,select_type,table,type,possible_keys,
key,key_len,ref,rows,Extra`)
values('1','SIMPLE','lps','index_merge','assigned_user_id,scheduled_payment_date,payment_status,deleted','deleted,assigned_user_id,payment_status','2,109,303',NULL,'23347','Using
intersect(deleted,assigned_user_id,payment_status); Using where');
You should match the data type of the preducate with the column. Because payment_type is DATE, make the BETWEEN values DATE also:
WHERE payment_date BETWEEN
CURDATE() AND LAST_DAY(CURDATE())
Matching types ensures the index will be used.
In contrast, your query is using DATE_FORMAT(), which produces a text data type, so in order to perform the comparison, mysql is converting the payment_dare column to text, so it can't use the index (the index contains DATE values, not text values), so every single row is converted and compared.
If you are still having performance problems after making the change above, execute this:
ANALYZE TABLE payment_table;
Which will check the distribution of values in the indexed columns, which helps mysql make the right choice of index.