Between Dates Query - sql

I had a question up earlier and it was pretty much solved expect one part of it. for some reason its not showing me between dates for my query. Just the dates that i enter in the parameter. i was wondering if anyone can see any problem with the code. Any help is much appreciated.
Relationships
SELECT *
FROM Vehicles
WHERE Vehicles.vehicle_id NOT IN (
SELECT Booking.[vehicle id]
FROM Booking
WHERE (
[Enter Start Date] BETWEEN booking.start_rent_date
AND booking.end_rent_date
)
OR (
[Enter End Date] BETWEEN booking.start_rent_date
AND booking.end_rent_date
)
);

It's supposed that [Enter End Date] is greater than [Enter Start Date].
First, try if this single query works fine:
SELECT Booking.*
FROM Booking
WHERE (((Booking.start_rent_date)>#2016/11/1#)
AND ((Booking.end_rent_date)<#2016/11/20#));
Second, try to join with distinct values:
SELECT *
FROM Vehicles
WHERE Vehicles.vehicle_id NOT IN
(
SELECT distinct Booking.[vehicle id]
FROM Booking
WHERE (((Booking.start_rent_date)>#2016/11/1#)
AND ((Booking.end_rent_date)<#2016/11/20#))
);

Related

Converting Different columns into rows in SQL Server

I have data in SQL Server that needs to be converted from columns into rows. Now although this question has been asked quite a lot in sometime, I was still facing some difficulty and hence I was wondering if someone can assist me.
Currently the format is as below.
The table format that is required and that will be very helpful will be;
So not only the PIVOT needs to be applied but I am not sure which SQL Query syntax will help to identify the Type. I have tried using CASE-WHEN with PIVOT but that really yield correct output.
Regards!
You can use CROSS APPLY query like below
see working demo
Select
ProjectName,
v.*
from t
cross apply
(
values
('Plan',PlanStartDate,PlanEndDate),
('Actual',ActualStartDate, ActualEndDate)
)v(type,StartDate, EndDate)
Try this
;WITH CTE2(ProjectName,[Plan Start Date],[Plan End Date],[Actual Start Date],[Actual End Date])
AS
(
SELECT 'PR-A','1/1/2006','1/4/2006','1/4/2007','1/5/2008' UNION ALL
SELECT 'PR-B','1/1/2007','1/1/2008','4/4/2008','6/6/2008' UNION ALL
SELECT 'PR-C','1/1/2004','1/1/2008','2/5/2001','2/2/2008'
)
SELECT Projectname,
'Plan' AS [Type],
[Plan start date] AS [Start Date],
[Plan end date] AS [End Date]
FROM Cte2
UNION ALL
SELECT Projectname,
'Actual' AS [Type],
[Actual start date],
[Actual end date]
FROM Cte2
ORDER BY Projectname,
[Type] DESC
Demo :http://rextester.com/CQEBV76844

Extract a specific line from a SELECT statement based on the last Trasanction date

Good day,
I have an SQL code that return to me all quantities that I received over time, but I want to display only the latest one
SELECT * FROM
(SELECT DISTINCT
[dbo].[ttcibd001110].[t_cmnf] AS [Manufacturer],
[dbo].[ttcibd001110].[t_item] AS [Item code],
[dbo].[ttcibd001110].[t_dsca] AS [Description],
[dbo].[ttcibd001110].[t_seak] AS [Search key 1],
[dbo].[twhinr110110].[t_trdt] AS [Transaction date],
[dbo].[twhinr110110].[t_cwar] AS [Warehouse],
[dbo].[twhinr110110].[t_qstk] AS [Quantity Inventory Unit]
FROM [dbo].[twhinr110110] LEFT JOIN [dbo].[ttcibd001110]
ON [dbo].[twhinr110110].[t_item]=[dbo].[ttcibd001110].[t_item]
WHERE [dbo].[twhinr110110].[t_koor]='2' AND [dbo].[ttcibd001110].[t_cmnf]='ManufacturerX') AS tabel
WHERE ltrim(tabel.[Item code])='1000045'
Now, from this selection I want to select only the line with the latest Transaction date, but I am stuck.
Can somebody help me in this way?
Thank you!
Change your beginning to
SELECT TOP 1
and after where use
ORDER BY [Transaction date] DESC

how get the count if the customer has activated certs three times in same year with SP

I have got DB table schema ActInfo like this
customerName customerEmail CertificateID Activated_On
A A#xxx.com xxxx 2013-05-20 04:02:39.000
A A#xxxx.com xxxxx 2013-09-11 03:09:34.000
A A#xxxx.com xxxxx 2013-04-03 06:09:34.000
We can see from above data that A has activated certificate three times in a year but i need to give a warning that he has activated three times per year
Is it possible with storedprocedure to check the count if user has activated the certificate more than twice in same year...Certificate ID are same or not it does not matter.
Would any one please help on this query
Many thanks for advance...
In this approach, I start with the most recent activation per customer, then outer join to all the activations for that customer within the past year. We ultimately return the customer and the count of activations within the past year.
SELECT
DerivedLastActivationByCustomer.CustomerName AS [Customer Name],
COUNT(ActInfo.CustomerName) AS [Activations in Past Year]
FROM
(
SELECT
CustomerName,
MAX(Activated_On) AS [Last Activation]
FROM
ActInfo
GROUP BY
CustomerName
) DerivedLastActivationByCustomer
LEFT OUTER JOIN ActInfo ON DerivedLastActivationByCustomer.CustomerName = ActInfo.CustomerName AND DATEDIFF(d, ActInfo.ActivatedOn, DerivedLastActivationByCustomer.[Last Activation]) < 365
GROUP BY
DerivedLastActivationByCustomer.CustomerName
Now, if you want to turn this into a stored procedure, you have options. You don't specify how this SP should work. In the simplest possible form, you could use just the above query and return the recordset.
Or, you could take the customer as an input parameter (i.e. #Cust), then use it as part of the WHERE clause of the inner query to only return info on that one specific customer.
Another possible approach would be to put a WHERE clause on the outermost SELECT statement to only return those with three or more activations (i.e. WHERE [Activations in Past Year] >= 3
Based on comments, the SP would be:
CREATE PROCEDURE [dbo].[GetActivationsInPriorYear]
(
#Cust nvarchar(max),
#ActivationCount int OUTPUT
)
AS
SELECT
DerivedLastActivationByCustomer.CustomerName AS [Customer Name],
#ActivationCount = COUNT(ActInfo.CustomerName) --AS [Activations in Past Year]
FROM
(
SELECT
CustomerName,
MAX(Activated_On) AS [Last Activation]
FROM
ActInfo
WHERE
ActInfo.CustomerName = #Cust
GROUP BY
CustomerName
) DerivedLastActivationByCustomer
LEFT OUTER JOIN ActInfo ON DerivedLastActivationByCustomer.CustomerName = ActInfo.CustomerName AND DATEDIFF(d, ActInfo.ActivatedOn, DerivedLastActivationByCustomer.[Last Activation]) < 365
GROUP BY
DerivedLastActivationByCustomer.CustomerName
GO

SQL Query - Query on Current Date but condition from the past

I am looking for help with the following scenario:
I have an SQL Server DB, with a table that stores historical data. For example lets use the following as a sample set.
CAR, SERVICE DATE, FINDINGS
1234, 21/01/2001, Fuel Filter
1234, 23/09/2009, Oil Change
1234, 30/09/2015, Tyres
3456, 30/09/2015, Clutch
I would like from the following sample to bring back the result that shows the service of any car that was brought in on a give date, e.g. 30/09/2015 but only if it had an oil change in the past.
The query would only bring back:
1234, 30/09/2015, Tyres
since it is the only car on that date to be services that previously had an oil change.
Any help would be greatly appreciated.
Use an EXISTS clause:
SELECT cur.car,
cur.[service date],
cur.findings
FROM tablename cur
WHERE cur.[service date] = #mydate
AND EXISTS (
SELECT 1
FROM tablename past
WHERE past.car = cur.car
AND past.[service date] < cur.[service date]
AND past.findings = 'oil change'
)
I would do it as a cte.
Find the list of cars that have had oil changed, then join back onto the original table to find the intersection.
DECLARE #date datetime;
SET #date = '20150930'
with oil_Cte as (
select distinct car from
tableName
where findings = 'oil change'
and date < #date
)
select *
from tableName
inner join oil_cte on tableName.car = oil_cte.car
where date = #date
This question had many conditions like
One of the service should happen on specified date.
Previous service to that date shoule only be 'Oil Change'. If previous service is not 'Oil Change' then don't include it in result,
even if it meets condition 1. Along with this, if car has record of
OIL Chagne in past then it doesn't matter.
If car had OIL CHANGE record but don't have service on that date then it should not consider.
You can try this solution.. and here is the working SQLFiddle for you
select * from #t where car in (
select car from (
select car, [service date], findings, ROW_NUMBER() over (Partition by car order by [Service Date] desc) as [row]
from (select * from #t where car in (select car from #t where [service date] = '2015-09-30')) A) T
where T.row =2 and Findings = 'Oil Change'
) and [service date] = '2015-09-30'

Access 2010 -- query to determine inclusion in date range

I am a newbie to both SQL and Access and was wondering if you could help please?
I am in the process of creating a hotel bookings database using Access 2010 but I cannot get my query working where I search for a vacant room.
My database has 5 tables as follows (Field Names in brackets):
BOOKINGS (BookRef, CustAcctNo, BookDate, ArrivDate, DurStay, EmpNo, RoomNo)
CUSTOMERS (CustAcctNo, Title, Forename, Surname, Address1, Address2, Address3)
EMPLOYEES (EmpNo, Title, Forename, Surname)
ROOM TYPES (RoomType, Description, Rate/Price)
ROOMS (RoomNo, RoomType)
These tables all have a 'one-to-many' relationship i.e. one customer can have many bookings.
So, my thinking is that the Fields of interest would be the ArrivDate Field (date of arrival) and DurStay (Duration of Stay) Field. In the Rooms table the Room Number is the Field I am calling out.
So, the closest I have got so far is the following:
PARAMETERS [Start Date] DateTime, [End Date] DateTime;
SELECT R.*, [Start Date] AS Expr1, [End Date] AS Expr2, *
FROM ROOMS AS R
LEFT JOIN (SELECT B.RoomNo
FROM Bookings AS B
WHERE ([Start Date] between B.ArrivDate and (B.ArrivDate + [Please Enter]))
AND ([End Date] between B.ArrivDate and (B.ArrivDate + B.DURSTAY))) AS BKD
ON R.RoomNo = BKD.RoomNo
WHERE (((BKD.RoomNo) Is Null));
This just doesn't seem to be working for me at all. I have tried many times with different versions of the above code but seem to be getting nowhere. My thoughts were that I do a search where the field is null between the dates plus the duration of stay but maybe I am going about it the wrong way I am not sure.
Hopefully I have provided enough detail here but please let me know if you need to know more. I really appreciate you all having a look at this at least. Maybe a fresh outlook on it might spot where I am going wrong.
Many thanks in advance for any help you can offer.
Try changing from this:
WHERE ([Start Date] between B.ArrivDate and ...
AND ([End Date] between B.ArrivDate and ...
to this:
WHERE ([Start Date] between B.ArrivDate and ...
OR ([End Date] between B.ArrivDate and ...
I think this fulfills the logic better because it accepts a partial match, that is, an overlap in dates.
PARAMETERS [Start Date] DateTime, [End Date] DateTime;
SELECT R.*, [Start Date] AS Expr1, [End Date] AS Expr2, *
FROM ROOMS AS R
LEFT JOIN (SELECT B.RoomNo
FROM Bookings AS B
WHERE ([Start Date] between B.ArrivDate and (B.ArrivDate + **B.DURSTAY**))
**OR** ([End Date] between B.ArrivDate and (B.ArrivDate + B.DURSTAY))) AS BKD
ON R.RoomNo = BKD.RoomNo
WHERE (((BKD.RoomNo) Is Null));
or
an easier, more elegant query would be something like:
SELECT R.*, #06/05/2014# as [Start Date] , #06/10/2014# as [End Date]
FROM ROOMS AS R
WHERE R.RoomNo not in
(
SELECT DISTINCT RoomNo FROM Bookings B
WHERE (#06/05/2014# between B.Arrival and (B.Arrival + B.Duration))
OR (#06/10/2014# between B.Arrival and (B.Arrival + B.Duration))
);
The date parameters must be passed in the american format (#MM/DD/YYYY#)