Bulk insert with variable date field for non existing dates? - tsql

Attendence
(
Stu_id int
Att_Id int
Att_Date datetime
Att_Num numeric(15,5)
)
This table basically contains attendence records. I am trying to find the logic to enter the rows for missing dates from 1 Jan 2012 till today.
Assume there is a single attendence record for this period row (1,1,'2012-05-06',1.20000). Then I would like to insert rows for each day from 1 Jan 2012 till today except the existing date with the same values for all the fields except the date field which should be the actual date.
I am trying to bulk insert all the rows but don't know how would I adjust the date field
and check for the existing date.
Thanks.

Try a stored procedure which loops through the dates.
Or better yet, make a dates table and select from that. This will be much faster. Something like:
INSERT INTO Attendence (Stu_id, Att_Id, Att_Date, Att_Num)
SELECT a.Stu_id, a.Att_Id, d.TheDate, a.Att_Num
FROM Attendence a
INNER JOIN Dates d ON d.TheDate BETWEEN '2012-01-01' AND GETDATE()
AND d.TheDate <> a.Att_Date

I would use the DateDiff function to figure out the amount of days inbetween the date in the function and the date in question. Make a DateTime variable and give it the value of 1 Jan 2012. Then set up a while loop that loops the amount of days from the DateDiff function.
In psuedo, the while loop would look something like this.
#DaysTill = DateDiff(days, 1/1/2012, #SomeDate)
While #DaysTill>0
##Check = Select Count(Att_Date) From Attendance where AttDate = DateAdd(days, #DaysTill, Jan 1st 2012)
IF ##Check = 0 THEN Insert Into Attendance VALUES #Stu, #Id, DateAdd(days, #DaysTill, Jan 1st 2012), #numeric
#DaysTill = #DaysTill - 1
END
The main things are understanding DateAdd and DateDiff. After that everything becomes relatively simple.

Related

Find all instances of a date in a date range - SQL Server

I need to find the price for an item for each financial year end date in a date range. In this case the financial year is e.g. 31 March
The table I have for example:
ItemID
Value
DateFrom
DateTo
1
10
'2019/01/01'
'2021/02/28'
1
11
'2021/03/01'
'2021/05/01'
SQL Fiddle
The SQL would thus result in the above table to be:
ItemID
Value
DateFrom
DateTo
1
10
'2019/01/01'
'2019/03/30'
1
10
'2020/03/31'
'2021/02/28'
1
11
'2020/03/01'
'2021/03/30'
1
11
'2020/03/31'
'2021/05/01'
You can solve it, but a prerequisite is the creation of a table called financial_years and filling it with data. This would be the structure of the table:
financial_years(id, DateFrom, DateTo)
Now that you have this table, you can do something like this:
select ItemID, Value, financial_years.DateFrom, financial_years.DateTo
from items
join financial_years
on (items.DateFrom between financial_years.DateFrom and financial_years.DateTo) or
(items.DateTo between financial_years.DateFrom and financial_years.DateTo)
order by financial_years.DateFrom;
The accepted answer is not correct, as it does not split out different parts of the year which have different values.
You also do not need a Year table, although it can be beneficial. You can generate it on the fly using a VALUES table.
Note also a better way to check the intervals overlap, using AND not OR
WITH Years AS (
SELECT
YearStart = DATEFROMPARTS(v.yr, 3, 31),
YearEnd = DATEFROMPARTS(v.yr + 1, 3, 31)
FROM (VALUES
(2015),(2016),(2017),(2018),(2019),(2020),(2021),(2022),(2023),(2024),(2025),(2026),(2027),(2028),(2029),(2030),(2031),(2032),(2033),(2034),(2035),(2036),(2037),(2038),(2039)
) v(yr)
)
SELECT
i.ItemID,
i.Value,
DateFrom = CASE WHEN i.DateFrom > y.YearStart THEN i.DateFrom ELSE y.YearStart END,
DateTo = CASE WHEN i.DateTo > y.YearEnd THEN y.YearEnd ELSE i.DateTo END
FROM items i
JOIN Years y ON i.DateFrom <= y.YearEnd
AND i.DateTo >= y.YearStart;

Number of days in a month in DB2

Is there a way to find the number of days in a month in DB2. For example I have a datetime field which I display as Jan-2020, Feb-2020 and so on. Based on this field I need to fetch the number of days for that month. The output should be something like below table,
I'm using the below query
select reportdate, TO_CHAR(reportdate, 'Mon-YYYY') as textmonth from mytable
Expected output
ReportDate textMonth No of Days
1-1-2020 08:00 Jan-2020 31
1-2-2020 09:00 Feb-2020 29
12-03-2020 07:00 Mar-2020 31
Try this:
/*
WITH MYTABLE (reportdate) AS
(
VALUES
TIMESTAMP('2020-01-01 08:00:00')
, TIMESTAMP('2020-02-01 09:00:00')
, TIMESTAMP('2020-03-12 07:00:00')
)
*/
SELECT reportdate, textMonth, DAYS(D + 1 MONTH) - DAYS(D) AS NO_OF_DAYS
FROM
(
SELECT
reportdate, TO_CHAR(reportdate, 'Mon-YYYY') textMonth
, DATE(TO_DATE('01-' || TO_CHAR(reportdate, 'Mon-YYYY'), 'dd-Mon-yyyy')) D
FROM MYTABLE
);
Db2 has the function DAYS_TO_END_OF_MONTH and several others which you could use. Based on your month input, construct the first day of the month. This should be something like 2020-01-01 for Jan-2020 or 2020-02-01 for Feb-2020. Follow the link for several other conversion functions which allow you to transform between formats and to perform date arithmetics.
convert your column to a proper date and try this: day(last_day(date_column))

SQL Syntax for Date that exist in on year but not in Another

I'm trying to write a query that would give me the records of all members that have Order dates that exist in 2013 but not in 2014. When I write my query it gives me ALL of the 2013 records which still exist in 2014. I'm trying to get ONLY record that have order dates in 2013 and not in 2014. So it should show records which exist in 2013 and exclude records that do not exist in 2014. Please help as I'm really new to SQL.
Thank you very much.
Below is my query:
SELECT
OMFMC.BILL_MASTER_CUSTOMER_ID,
OMFMC.BILL_FIRST_NAME,
OMFMC.BILL_LAST_NAME,
CMI.NATIONAL_LEVEL2,
MIN(OMFMC.ORDER_DATE),
OMFMC.ORDER_DATE,
FT.PAYMENT_AMOUNT,
SUM(FT.PAYMENT_AMOUNT)as SUM
FROM
CUSTOMER CUSTOMER_IN_TRIBUTE_TO
RIGHT OUTER JOIN ORDER_FND_DETAIL OFD
ON (CUSTOMER_IN_TRIBUTE_TO.MASTER_CUSTOMER_ID=OFD.IN_TRIBUTE_TO_MAST_CUST
and CUSTOMER_IN_TRIBUTE_TO.SUB_CUSTOMER_ID=OFD.IN_TRIBUTE_TO_SUB_CUST)
RIGHT OUTER JOIN ORDER_MBR_FND_MTG_CUS_INFO_VW OMFMC
ON (OMFMC.ORDER_NO=OFD.ORDER_NO
and OMFMC.ORDER_LINE_NO = OFD.ORDER_LINE_NO )
LEFT OUTER JOIN CUS_CURRENT_MEMBERSHIP_INFO CMI
ON (CMI.MASTER_CUSTOMER_ID=OMFMC.BILL_MASTER_CUSTOMER_ID
and CMI.SUB_CUSTOMER_ID=OMFMC.BILL_SUB_CUSTOMER_ID)
LEFT OUTER JOIN FAR_TXN FT
ON (FT.ORDER_NO=OMFMC.ORDER_NO
and FT.ORDER_LINE_NO=OMFMC.ORDER_LINE_NO)
WHERE
OMFMC.ORDER_STATUS_CODE='A'
AND OMFMC.LINE_STATUS_CODE = 'A'
AND OMFMC.ORDER_STATUS_CODE = 'A'
AND OMFMC.LINE_STATUS_CODE = 'A'
AND OMFMC.ORDER_DATE BETWEEN '1/1/2013' and '12/31/2013'
AND OMFMC.ORDER_DATE Not BETWEEN '1/1/2014' and '12/31/2014'
AND OMFMC.BILL_CUSTOMER_CLASS_CODE NOT IN ( 'TEST_MBR','STAFF' )
AND FUND in ('FOSFN' , 'MFUND')
GROUP BY
OMFMC.BILL_MASTER_CUSTOMER_ID,
OMFMC.BILL_FIRST_NAME,
OMFMC.BILL_LAST_NAME,
OMFMC.BILL_LABEL_NAME,
OMFMC.BILL_PRIMARY_EMAIL_ADDRESS,
OMFMC.BILL_ADDRESS_1,
OMFMC.BILL_ADDRESS_2,
OMFMC.BILL_CITY,
OMFMC.BILL_STATE,
OMFMC.BILL_POSTAL_CODE,
CMI.NATIONAL_LEVEL2,
OMFMC.ORDER_DATE,
FT.PAYMENT_AMOUNT
HAVING SUM(FT.PAYMENT_AMOUNT) < 0
Order By BILL_MASTER_CUSTOMER_ID
In the order dates field, there are dates that have 2013, and 2014 dates. I want a my query to look at 2013 and 2014 order dates and ONLY pull out order dates that are in 2013. Not the records that have 2013 and 2014 dates. If they have an order in 2013 AND 2014 then I want to exclude those records. So for example:
enter code here
Bill_Member_ID..........Order_Date
123....................01/05/2013
123.................... 01/27/2013
123.................... 02/15/2014
123.................... 02/18/2014
456.................... 01/07/2013
789.................... 01/05/2013
789.................... 02/17/2014
992.................... 03/15/2013
So then I should get a return of
Bill_Member_ID..........Order_Date
456.................... 01/07/2013
992.................... 03/15/2013
Thank you so much
What you need is a simple subselect, and to feed its results into your outermost select to display the results.
What you are after is the list of Bill_Member_ID who have an order date between 2013-01-01 and 2013-12-31 (inclusive) but do not have an order dates in between 2014-01-01 and 2014-12-13. So, let's build our pseudo-code select. We do this inside out (starting at the innermost, and working our way to the outermost layer of the select).
First up, generate a list of Members who have orders in 2014. So that's
Select Bill_Member_ID
From Order_Table
WHERE Year( OrderDate ) = '2014';
We feed that as a condition to the next select. This next layer's job is to select all the Members who have an OrderDate in 2013, but not in 2014.
Select Bill_Member_ID
From Order_Table
WHERE Year( OrderDate ) = '2013' AND Bill_Member_ID Not In
(
Select Bill_Member_ID
From Order_Table
WHERE Year( OrderDate ) = '2014'
)
This yields your list of Bill_Member_ID who have orders in 2013, but not in 2014. Add the additional columns you need for your final select. Also, add in your other filtering conditions (ie, the not Test and not Staff) to narrow the results as needed.
That's really all you need to do to generate your list of sought customers. If you aren't using a database that does not supports just specifying the year, then you'll need to use the between dates to filter the where date field in range of condition.

Insert Column with value (#days) between dates in other columns

I have two columns; CommencementDate and ExpectedCompletionDate. I would like to insert a column (Days) which gives the number of days between the two date columns in my table.
I'm not sure where to start. I'm on day 5 of writing queries!
You just have to substract ExpectedCompletionDate and CommencementDate and return the days of that.
SELECT DATEDIFF(Day, ExpectedCompletionDate, CommencementDate);
Also you can return the absolute value to ensure this is a positive value.
SELECT ABS(DATEDIFF(Day, ExpectedCompletionDate, CommencementDate));
You can see the documentation in microsft
http://technet.microsoft.com/en-us/library/ms189794.aspx -> Datediff
http://technet.microsoft.com/en-us/library/ms189800.aspx -> ABS

How can I compare two datetime fields but ignore the year?

I get to dust off my VBScript hat and write some classic ASP to query a SQL Server 2000 database.
Here's the scenario:
I have two datetime fields called fieldA and fieldB.
fieldB will never have a year value that's greater than the year of fieldA
It is possible the that two fields will have the same year.
What I want is all records where fieldA >= fieldB, independent of the year. Just pretend that each field is just a month & day.
How can I get this? My knowledge of T-SQL date/time functions is spotty at best.
You may want to use the built in time functions such as DAY and MONTH. e.g.
SELECT * from table where
MONTH(fieldA) > MONTH(fieldB) OR(
MONTH(fieldA) = MONTH(fieldB) AND DAY(fieldA) >= DAY(fieldB))
Selecting all rows where either the fieldA's month is greater or the months are the same and fieldA's day is greater.
select *
from t
where datepart(month,t.fieldA) >= datepart(month,t.fieldB)
or (datepart(month,t.fieldA) = datepart(month,t.fieldB)
and datepart(day,t.fieldA) >= datepart(day,t.fieldB))
If you care about hours, minutes, seconds, you'll need to extend this to cover the cases, although it may be faster to cast to a suitable string, remove the year and compare.
select *
from t
where substring(convert(varchar,t.fieldA,21),5,20)
>= substring(convert(varchar,t.fieldB,21),5,20)
SELECT *
FROM SOME_TABLE
WHERE MONTH(fieldA) > MONTH(fieldB)
OR ( MONTH(fieldA) = MONTH(fieldB) AND DAY(fieldA) >= DAY(fieldB) )
I would approach this from a Julian date perspective, convert each field into the Julian date (number of days after the first of year), then compare those values.
This may or may not produce desired results with respect to leap years.
If you were worried about hours, minutes, seconds, etc., you could adjust the DateDiff functions to calculate the number of hours (or minutes or seconds) since the beginning of the year.
SELECT *
FROM SOME_Table
WHERE DateDiff(d, '1/01/' + Cast(DatePart(yy, fieldA) AS VarChar(5)), fieldA) >=
DateDiff(d, '1/01/' + Cast(DatePart(yy, fieldB) AS VarChar(5)), fieldB)
Temp table for testing
Create table #t (calDate date)
Declare #curDate date = '2010-01-01'
while #curDate < '2021-01-01'
begin
insert into #t values (#curDate)
Set #curDate = dateadd(dd,1,#curDate)
end
Example of any date greater than or equal to today
Declare #testDate date = getdate()
SELECT *
FROM #t
WHERE datediff(dd,dateadd(yy,1900 - year(#testDate),#testDate),dateadd(yy,1900 - year(calDate),calDate)) >= 0
One more example with any day less than today
Declare #testDate date = getdate()
SELECT *
FROM #t
WHERE datediff(dd,dateadd(yy,1900 - year(#testDate),#testDate),dateadd(yy,1900 - year(calDate),calDate)) < 0