how to get dates between two given dates in sql - php

in the above table i need sql query by which i can return dates between Leave_from and Leave_to from leave_log Table (eg, Leave_from 30/07/2018 Leave_to 02-08-2018) i need dates like
30/07/2018
01/08/2018
02/08/2018
by which i will try next query
2) is der any query or function which will check before insert into leave_log table whether the leaves applied by the employees for particular date (01-08-2018) does not cross quota of 10% per Team
Thanks in advance

First, you should have a calender table if yes, then you need to JOIN with your actual table to calender table. In other way you can use recursive CTE option :
with t as (
select id, leave_frm, leave_to
from table
union all
select id, dateadd(day, 1, leave_frm), leave_to
from t
where leave_frm < leave_to
)
select *
from t
option (maxrecursion 0);

Related

get monthwise row count from datewise data in mysql

I have two tables:
table 1.a
id--entry_date-amount
============================
2---2016-04-14--$400
3---2016-04-14--$400
4----2017-07-14--$200
5---2017-07-14--$500
6---2017-05-14--$600
7----2017-06-18--$100
table 2.b
id--entry_date
===========================
2---2016-04-14--$230
3---2016-04-14--$230
4----2017-07-14--$567
5---2017-07-14--$600
6---2017-05-14--$560
7----2017-06-18--$90
8---2016-04-14--$100
from the two tables how can i get count with montwise
my desired result:
month_name--total(count form table a)--total(count form table b)--amount(table a)--amount(table b)
========================================================
April,16-----------2-------------------3---$800-$500
May,17-----------1-------------------1 --$600--$700
June,17-----------2-------------------2--$100--$800
July,17-----------2-------------------2---$700-$400
this is the demo data.
I want to show data from two tables in a single query month wise.
How can i do this?
I tried:
SELECT MONTHNAME(r.entry_date),r.a_total FROM(
SELECT
IFNULL((SELECT COUNT(tr.id) AS amount FROM a AS tr WHERE MONTH(tr.entry_date)=MONTH(t.entry_date)),0) AS a_total
,t.entry_date
FROM(SELECT tr.id,tr.entry_date
FROM a AS tr
WHERE DATE(tr.entry_date) BETWEEN '2017-07-01' AND '2018-06-30') t
GROUP BY MONTH(t.entry_date)) r
But takes 58 seconds for simple query. How can i make this in a simple query?
You can get the counts and sum from each table individually, then use UNION to combine the two result sets into one result set. Something like this :
SELECT Month_name,
SUM(aCount) AS aCount,
SUM(bCount) AS bCount,
SUM(aAmount) AS aAmount,
SUM(bAmount) AS bAmount
FROM
(
SELECT
MONTHNAME(a.entry_date) AS Month_name,
COUNT(a.id) AS aCount,
0 AS bCount,
SUM(a.amount) AS aAmount,
0 AS bAmount
FROM a
GROUP BY MONTHNAME(a.entry_date)
UNION ALL
SELECT
MONTHNAME(b.entry_date) AS Month_name,
0 AS aCount,
COUNT(b.id) AS bCount,
0 AS aAmount,
SUM(b.amount) AS bAmount
FROM b
GROUP BY MONTHNAME(b.entry_date)
) AS t
GROUP BY Month_Name;
live demo
user9131497 has a good design for the big picture. However, I would suggest stuff like this for handling the dates:
SELECT DATE_FORMAT(entry_date, "%M,%y") AS 'Month',
COUNT(*) AS 'aCount'
FROM a
GROUP BY LEFT(entry_date, 7) -- eg, "2017-03"
Try that to see what I mean.
Note that this will work beyond a year. Or did you need January values from all years to be combined?? -- That's what your solution and user9131497's will do. Mine keeps them separate.

SQL: How to select one row per day

I have a database that has a row entry for every minute (86,000 values per day) and I am trying to write PHP to select only one row per day. I have a column "timestamp" that has the current timestamp in regular format (2017-12-09 06:49:02).
Does anyone know how to write a select statement to do what I am trying to do?
Example output:
2017-12-09 06:49:02, datavalue
2017-12-10 06:49:02, datavalue
2017-12-11 06:49:02, datavalue
2017-12-12 06:49:02, datavalue
Here is one method:
select t.*
from t join
(select min(t2.timestamp) as min_timestamp
from t t2
group by date(t2.timestamp)
) t2
on t.timestamp = t2.min_timestamp;

Joining sql query with three tables

I have to join three tables.
1 table is transaction , next table is shops, 3rd is weather.
I want to fetch data from all of these three ,but in case of weather table > id,tamp_c,datetime column name .
The query is:-
select HOUR(transaction.time) as Hour ,
TRUNCATE(sum(transaction.total),2) as Total_Sales,
shops.gstIncludedSales as GST_Inc_Sales,
shops.gstFreeSales as GST_Free,weather.temp_c
from transaction,shops,weather
where transaction.shopid=shops.id and transaction.shopid=7
and transaction.transaction_date ='2015-05-25'
group by hour
ORDER BY hour DESC
The problem is that I want to apply a where clause with weather.datetime table separation for particular date like time(datetime)='2015-05-25', but it's not working.
Try this:
WHERE transaction.transaction_date >= '2015-05-25' AND transaction.transaction_date < '2015-05-26'
That will return rows with timestamp during the whole day (midnight until midnight - time is implied).
If you have SQLServer 2014 you canm use DATE(transaction.transaction_date).
Does this do what you want
SELECT HOUR(transaction.time) as Hour ,
TRUNCATE(sum(transaction.total),2) as Total_Sales,
shops.gstIncludedSales as GST_Inc_Sales,
shops.gstFreeSales as GST_Free,weather.temp_c
FROM transaction
JOIN shops ON transaction.shopid=shops.id
JOIN weather ON DATE(transaction.transaction_date) = DATE(weather.datetime)
WHERE DATE(transaction.transaction_date)='2015-05-25' AND transaction.shopid=7
GROUP by hour
ORDER BY hour DESC
(Assuming you are using MySQL)

How can I create a SUM of one column within a query in SQL?

I have one table with multiple columns. I am needing to create an SQL query to display certain columns based off of the user input from a datepicker and a select box. I have done that just fine. However, I am needing one of the result columns to be totaled at the bottom of the display table. I cannot figure out how to create a result within my current query to display the totaled column. Essentially, I would like the WTTotal column to be totaled into a separate cell. My current query is below. I really think this is something simple that I just can't seem to see.
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy,WTTotal
FROM WorkTicket
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
ORDER BY Client
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy,WTTotal
FROM WorkTicket
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
ORDER BY Client
UNION ALL
SELECT 'Total', NULL, NULL, NULL, NULL, SUM(WTTotal)
FROM WorkTicket
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL;
You can't have it with a single query. Putting a SUM() into your query would require a GROUP BY clause and collapse all of your original result rows down into a single result row - meaning your table would disappear. What you want a is a client-side solution. e.g. Start a counter in your client code and manually add up the results. In pseudoish-code:
$sum = 0;
while( $row = fetch_from_db() ) {
$sum += $row['field_to_sum'];
display_row();
}
echo "Total: $sum";
If you want to have it in a separate column, not in a separate row, either you calculate it in a subquery and join it to your result:
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy, my_calculated_sum AS WTTotal
FROM WorkTicket
JOIN (SELECT SUM(whatever_you_want_to_sum) as my_calculated_sum FROM WorkTicket) subquery_alias
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
ORDER BY Client
Or you just calculate it with variables, like a running total. Your result is in the last row of the column.
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy, #sum_variable := #sum_variable + whatever_you_want_to_sum AS WTTotal
FROM WorkTicket
, (SELECT #sum_variable := 0) var_init_subquery
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
ORDER BY Client
But actually Kevin's solution is very good.
I also have similar solution as Kevin's :
;with cte_result
as
(
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy,WTTotal
FROM WorkTicket
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
)
select *
from cte_result
union
select 'TotalAmount',NULL,NULL,NULL,NULL,sum(WTTotal)
from cte_result
order by client
but this solution will work only if your DB Engine supports CTE.
with a CTE, we can use same resultset to get total's row.

Select available rooms between two dates

I have above mysql table with available dates and prices. Second table includes room details. How can I join two tables to get available rooms between two dates and not get duplicate content.
This is hard to come up with a complete answer for you here, as you are only showing us the table which contains the bookings - we cannot know what range of rooms are available.
SQL which returns the room_id's for rooms which are booked for at least part of the selected period could be:
SELECT `room_id` , COUNT(*)
FROM `bookings`
WHERE `dt` BETWEEN "[start date]" AND "[end date]"
GROUP BY `room_id`;
If you had a table of rooms (rather than bookings), it would be possible for you to return a list of any rooms not booked during that period with:
SELECT `id`
FROM `rooms`
WHERE `id` NOT IN (
SELECT DISTINCT( `room_id` )
FROM `bookings`
WHERE `dt` BETWEEN "[start date]" AND "[end date]"
);
AMENDMENT
Based on the feedback by OP, the assumptions are now:
The table contains details of rooms which are available for a period starting on the date in column dt and ending the following day (ie hotel rooms)
The query should return any rooms which are available for the entirity of the period entered (so only rooms which are available from DAY A to DAY B will be returned.
As such, the amended code is:
SELECT room_id
FROM available_rooms
WHERE dt BETWEEN "[start date]" AND DATE_SUB("[end date]",INTERVAL 1 DAY)
GROUP BY room_id
HAVING COUNT(*)=ABS(DATEDIFF("[start date]","[end date]"));
SELECT available.* , rooms.* FROM available, rooms
WHERE available.room_id = rooms.room_id AND
available.dt BETWEEN '2005-01-01' AND '2005-12-31'
Assuming the table you showed us is called rooms_dates with two other tables rooms and room_details:
select room.id, room_details.xxxxxxx from rooms
inner join room_details on rooms.id = room_details.room_id
where rooms.id in
(
select distinct room_id from rooms_dates
where dt >= 'xxxx-xx-xx' and dt <= 'yyyy-yy-yy'
);

Categories