Use DATEDIFF in a case - case

I got a problem with my request.
I want to compare 2 dates, and if the number of days is inferior to 2, i want to display nothing. But if it's over, I want to display the days.
I got my request but it failed when I try to compare the DATEDIFF to 2.
SQL> SELECT noLivraison, noCommande, noArticle, dateCommande, quantite, dateLivraison, quantiteLivree,
CASE dateCommande
WHEN DATEDIFF(day, dateLivraison, dateCommande) < 2 THEN null
ELSE DATEDIFF(day, dateLivraison, dateCommande)
END nombreJoursEcoules
FROM Commande
NATURAL JOIN LigneCommande
NATURAL JOIN Livraison
NATURAL JOIN DetailLivraison 2 3 4 5 6 7 8 9
10 /
WHEN DATEDIFF(day, dateLivraison, dateCommande) < 2 THEN null
*
ERROR at line 3:
ORA-00905: missing keyword
I don't know how to fix it, I put more parenthesis but it didn't works.
Ty for reading.

You can try the below code , may be it will solve your problem
select col1,col2,case when DATEDIFF(dd, dateLivraison, dateCommande)
>= 2 then 'days' else null end as 'datefield', DATEDIFF(dd, dateLivraison,
dateCommande) as 'days' from tablename
Thanks

Related

Increase row number every time a flag changes

I have gone through a similar post in Stack overflow...
but my query is :
If my table generates a flag in run time execution,then how can I increase Grp_number(generate run time) every time my flag changes.
my Oracle query:
Select emp_id,
Case when MOD(rownum/3)=1 and rownum>1 then 'Y' else 'N' as flag
from Transaction_table
Desired o/p Data format:
emp_id Flag GRP_number
1 N 1
2 N 1
3 N 1
4 Y 2
5 N 2
6 N 2
7 Y 3
You cannot reference a column in another column in the same select list. You need to use sub query to avoid INVALID IDENTIFIER error.
Do it like -
WITH DATA AS(
SELECT emp_id,
CASE
WHEN MOD(rownum/3)=1
AND rownum >1
THEN 'Y'
ELSE 'N' AS flag
FROM Transaction_table
)
SELECT emp_id, flag, SUM(gap) over (PARTITION BY person
ORDER BY DAY) grp
FROM(
SELECT emp_id, flag,
CASE WHEN flag = lag(flag) over (PARTITION BY person
ORDER BY DAY)
THEN 0
ELSE 1
END gap
FROM DATA)

SQLite count(*) in while clause

I have a calendar table in which there are all the dates in the future and a workday field:
fld_date / fld_workday
2014-01-01 / 1
2014-01-02 / 1
2014-01-03 / 0
...
I want select a date which are n workday far from another date. I tried two ways, but i failed:
The 5th workday from 2014-11-07:
1.
SELECT n1.fld_date FROM calendar as n1 WHERE n1.fld_workday=1 AND
(select count(*) FROM calendar as n2 WHERE n2.fld_date>='2014-11-07' AND n2.fld_workday=1)=5
It gave back 0 row.
2.
SELECT fld_date FROM calendar WHERE fld_date>='2014-11-07' AND fld_workday=1 LIMIT 1 OFFSET 5
It's ok, but i would like to change the 5 days constant to a field, and it's cannot (it would be inside a bigger select statement):
SELECT fld_date FROM calendar WHERE fld_date>='2014-11-07' AND fld_workday=1 LIMIT 1 OFFSET fld_another_field
Any suggestion?
In the first query, the subquery does not refer to the row in n1.
You need a correlated subquery:
SELECT fld_Date
FROM Calendar AS n1
WHERE fld_WorkDay = 1
AND (SELECT COUNT(*)
FROM Calendar AS n2
WHERE fld_Date BETWEEN '2014-11-07' AND n1.fld_Date
AND fld_WorkDay = 1
) = 5
LIMIT 1
The subquery is extremly inefficient if there is no index on the fld_Date column.
You can avoid executing the subquery for every row in n1 by adding another condition with an estimate of the result date (assuming that there are between about four to five work days per week, and using a few extra days to be sure):
...
WHERE fldDate BETWEEN date('2014-11-07', (5 * 4/7 - 10) || ' days')
AND date('2014-11-07', (5 * 5/7 + 10) || ' days')
AND fldWorkDay = 1
AND (SELECT ...

How can I concatenate(or merge) values from 2 result sets with the same PK?

I don't know if I'm being dumb here but I can't seem to find an efficient way to do this. I wrote a very long and inefficient query that does what I need, but what I WANT is a more efficient way.
I have 2 result sets that displays an ID (a PK which is generic/from the same source in both sets) and a FLAG (A - approve and V - Validate).
Result Set 1
ID FLAG
1 V
2 V
3 V
4 V
5 V
6 V
Result Set 2
ID FLAG
2 A
5 A
7 A
8 A
I want to "merge" these two sets to give me this output:
ID FLAG
1 V
2 (V/A)
3 V
4 V
5 (V/A)
6 V
7 A
8 A
Neither of the 2 result sets will at any time have all the ID's to make a simple left join with a case statement on the other result set an easy solution.
I'm currently doing a union between the two sets to get ALL the ID's. Thereafter I left join the 2 result sets to get the required '(V/A)' by use of a case statement.
There must be a more efficient way but I just can't seem to figure it out now as I'm running low on amps... I need a holiday... :-/
Thanks in advance!
Use a FULL OUTER JOIN:
SELECT ID,
CASE
WHEN t1.FLAG IS NULL THEN t2.FLAG
WHEN t2.FLAG IS NULL THEN t1.FLAG
ELSE '(' || t1.FLAG || '/' || t2.FLAG || ')'
END AS MERGED_FLAG
FROM TABLE1 t1
FULL OUTER JOIN TABLE2 t2
USING (ID)
ORDER BY ID
See this SQLFiddle.
Share and enjoy.
I think that you can use xmlagg. Here an exemple :
SELECT deptno,
SUBSTR (REPLACE (REPLACE (XMLAGG (XMLELEMENT ("x", ename)
ORDER BY ename),'</x>'),'<x>','|'),2) as concated_list
FROM emp
GROUP BY deptno
ORDER BY deptno;
Bye

SQLITE syntax error performing an Update

I'm trying to improve a transit scheduling table by adding a column and flagging some rows to indicate they are the last stop for each trip.
Each trip will have many rows showing its stops and their sequence along the trip. I want to update the LastStop column with a '1' if the Sequence number is the highest for that trip.
I think the following SQL is on the right track but I am getting a "no such column: s1.stop_sequence" so I have no idea if I'm even on the right track until this unobvious to me error is resolved. I am a SQL lightweight barely beyond novice level. Stop_Sequence is definitely the correct name for the column.
UPDATE stop_times
SET LastStop = '1'
WHERE stop_sequence =(
SELECT max(st.stop_sequence)
FROM stop_times s1
WHERE s1.trip_id = trip_id
)
AND
trip_id = s1.trip_id
AND
stop_ID = s1.stop_id;
A simplified version of sample data is below.
TripID Stop Sequence LastStop
665381 1766 1
665381 3037 2
665381 3038 3 1
667475 1130 1
667475 2504 2 1
644501 2545 1
644501 3068 2
644501 2754 3
644501 3069 4
644501 2755 5 1
You cannot refer to a column in the subquery from the outer query.
Furthermore, the filter trip_id = s1.trip_id is duplicated, and you do not want to filter on stop_id because that would prevent the MAX from looking at any other stops of the trip.
Try this:
UPDATE stop_times
SET LastStop = '1'
WHERE Stop_Sequence = (SELECT MAX(Stop_Sequence)
FROM stop_times s1
WHERE s1.Trip_ID = stop_times.Trip_ID)
Alternatively, a last stop is a stop for which no other stop with a larger sequence number in the same trip exists:
UPDATE stop_times
SET LastStop = '1'
WHERE NOT EXISTS (SELECT 1
FROM Stop_Sequence s1
WHERE s1.Trip_ID = stop_times.Trip_ID
AND s1.Stop_Sequence > stop_times.Stop_Sequence)
This will work for you, as long as stops field is always less than 1000 (use bigger multiplier if it is):
UPDATE stop_times
SET laststop = 1
WHERE tripid*1000+sequence IN (
SELECT tripid*1000+sequence FROM (
SELECT tripid, max(sequence) AS sequence
FROM stop_times
GROUP BY 1
)
)
I would have written this using tuple syntax, but SQLite does not support it:
UPDATE stop_times
SET laststop = 1
WHERE (tripid, sequence) IN (
SELECT (tripid, sequence) FROM (
SELECT tripid, max(sequence) AS sequence
FROM stop_times
GROUP BY 1
)
)
Sorry, no SQLFiddle - it does not seem to work for me today.

Getting All the record of particular month - Building SQL Query

I need some help to build SQL Query. I have table having data like:
ID Date Name
1 1/1/2009 a
2 1/2/2009 b
3 1/3/2009 c
I need to get result something like...
1 1/1/2009 a
2 1/2/2009 b
3 1/3/2009 c
4 1/4/2009 Null
5 1/5/2009 Null
6 1/6/2009 Null
7 1/7/2009 Null
8 1/8/2009 Null
............................
............................
............................
30 1/30/2009 Null
31 1/31/2009 Null
I want query something like..
Select * from tbl **where month(Date)=1 AND year(Date)=2010**
Above is not completed query.
I need to get all the record of particular month, even if some date missing..
I guess there must be equi Join in the query, I am trying to build this query using Equi join
Thanks
BIG EDIT
Now understand the OPs question.
Use a common table expression and a left join to get this effect.
DECLARE #FirstDay DATETIME;
-- Set start time
SELECT #FirstDay = '2009-01-01';
WITH Days AS
(
SELECT #FirstDay as CalendarDay
UNION ALL
SELECT DATEADD(d, 1, CalendarDay) as CalendarDay
FROM Days
WHERE DATEADD(d, 1, CalendarDay) < DATEADD(m, 1, #FirstDay)
)
SELECT DATEPART(d,d.CalendarDay), **t.date should be (d.CalendarDay)**, t.Name FROM Days d
LEFT JOIN tbl t
ON
d.CalendarDay = t.Date
ORDER BY
d.CalendarDay;
Left this original answer at bottom
You need DATEPART, sir.
SELECT * FROM tbl WHERE DATEPART(m,Date) = 1
If you want to choose month and year, then you can use DATEPART twice or go for a range.
SELECT * FROM tbl WHERE DATEPART(m,Date) = 1 AND DATEPART(yyyy,Date) = 2009
Range :-
SELECT * FROM tbl WHERE Date >= '2009-01-01' AND Date < '2009-02-01'
See this link for more info on DATEPART.
http://msdn.microsoft.com/en-us/library/ms174420.aspx
You can use less or equal to.
Like so:
select * from tbl where date > '2009-01-01' and date < '2009-02-01'
However, it is unclear if you want month 1 from all years?
You can check more examples and functions on "Date and Time Functions" from MSDN
Create a temporary table containing all days of that certain month,
Do left outer join between that table and your data table on tempTable.month = #month.
now you have a big table with all days of the desired month and all the records matching the proper dates + empty records for those dates who have no data.
i hope that's what you want.

Resources