Write Query to Compare time in google fusion table - sql

I want to get all the entries from google fusion table which satisfies the condition in a given date
Time column > specific time
https://www.googleapis.com/fusiontables/v2/query?sql=SELECT * FROM 1WjowbI77j1WFcn3IEtbwBymhVZh8jfmP_dg1epd9 WHERE Date = '2015-02-23' AND Time > '10:25:04'&key=AIzaSyCALoSz00ZY3zTL1D_xUTD9GMb3T1ocBdU
But it gives me all the entries as result..
fusion table :
https://www.google.com/fusiontables/data?docid=1WjowbI77j1WFcn3IEtbwBymhVZh8jfmP_dg1epd9&key=AIzaSyCALoSz00ZY3zTL1D_xUTD9GMb3T1ocBdU#rows:id=1

It is assumed that the type of Time column is Date/Time and format is H:mm:ss AM/PM
In that case, it seems the filtering on Date/Time column is not supported.
According to Row and Query SQL Reference documentation:
Filtering on DATETIME
When filtering on a column of type DATETIME, the <value> should be
formatted as one of the following supported formats:
MMM dd, yy
MM/dd/yy
MM-dd-yy
MMM-dd-yy
yyyy.MM.dd
dd-MMM-yy
MMM/yy
MMM yy
dd/MMM/yy
yyyy
Having said that, you could consider to apply filtering to the returned results as demonstrates the following JavaScript example:
var key = 'AIzaSyCALoSz00ZY3zTL1D_xUTD9GMb3T1ocBdU'
var sql = "SELECT * FROM 1WjowbI77j1WFcn3IEtbwBymhVZh8jfmP_dg1epd9 WHERE Date = '2015-02-23'";
var requestUrl = "https://www.googleapis.com/fusiontables/v2/query?sql=" + sql + "&key=" + key;
var timeKey = '10:25:04';
$.getJSON(requestUrl, function(data) {
var filteredRows = data.rows.filter(function(row){
var dtCur = Date.parse(row[3] + ' ' + row[7]);
var dtKey = Date.parse(row[3] + ' ' + timeKey);
if (dtCur > dtKey) {
return row;
}
});
//print
var output = JSON.stringify(filteredRows, null, 2);
$("#output").text(output);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre style="background-color: #c0c0c0" id="output"></pre>

I can't tell you exactly what's going on there, the only issue I see that you've omited the AM(PM)
The documentation mentions the DateTime-Formats supported for filtering, but I think this part of the documentation is outdated(see: Date query with the current date between two date_time columns ).
For me it works as expected when I make a copy of the table(you may do the same):
https://www.googleapis.com/fusiontables/v2/query?sql=SELECT * FROM 12tl0d4jZRkhPD9ZdBzP2QzK4TyEu-U_Dnn8kimft WHERE Date = '2015-02-23' AND Time > '10:25:04 AM'&key=yourKey
Maybe they run a validation when a table will be copied and store DateTime-columns internally in another format.

Related

Search for exact string value in JSON

I have a column stored in JSON that looks like
column name: s2s_payload
Values:
{
"checkoutdate":"2019-10-31",
"checkindate":"2019-10-30",
"numtravelers":"2",
"domain":"www.travel.com.mx",
"destination": {
"country":"MX",
"city":"Manzanillo"
},
"eventtype":"search",
"vertical":"hotels"
}
I want to query exact values in the array rather than returning all values for a certain data type. I was using JSON_EXTRACT to get distinct counts.
SELECT
COUNT(JSON_EXTRACT(s2s_payload, '$.destination.code')) AS total,
JSON_EXTRACT(s2s_payload, '$.destination.code') AS destination
FROM
"db"."events_data_json5_temp"
WHERE
id = '111000'
AND s2s_payload IS NOT NULL
AND yr = '2019'
AND mon = '10'
AND dt >= '26'
AND JSON_EXTRACT(s2s_payload, '$.destination.code')
GROUP BY
JSON_EXTRACT(s2s_payload, '$.destination.code')
If I want to filter where ""eventtype"":""search"" how can I do this?
I tried using CAST(s2s_payload AS CHAR) = '{"eventtype"":""search"}' but that didn't work.
You need to use json_extract + a CAST to get actual value to compare against:
CAST(json_extract(s2s_payload, '$.eventtype') AS varchar) = 'search'
or, same with json_extract_scalar (and thus with no need for a CAST):
json_extract_scalar(s2s_payload, '$.eventtype')

MSSQL: Finding all items between two dates

I am creating a sails.js REST-API based on data in a MSSQL-database. Each record have a start date and an end date. I want to supply a query-date and find all records that are "started", but not "ended". So conceptually I'm thinking:
SELECT * FROM table WHERE
record_start_date <= query_date
AND
record_end_date >= query_date
In Waterline/Sails it looks like this:
Model.find({
record_start_date: { 'lessThanOrEqual': req.query.q + ' 00:00:00.0'},
record_end_date: { 'greaterThanOrEqual': req.query.q + ' 23:59:00.0' }
})
However this only gives me records that fall between them, not on the start og end date.
Looks like you need to swap the times inside the FIND:
Model.find({
record_start_date: { 'lessThanOrEqual': req.query.q + ' 23:59:00.0'},
record_end_date: { 'greaterThanOrEqual': req.query.q + ' 00:00:00.0' }
})
Consider the case where the record has start date 3/20 and end date 3/25. If you pass query date of 3/25, the record_end_date would not satisfy the greater-than-or-equal condition if you append the '23:59' to it (as you initially did).

SQL - Change Column A value when Column B is less than a certain value

Using sql query on a DB and importing information into another DB. So, I want to change the value of a column if the date in Column B is less than a certain value.
e.g.- If Column B is less than 01/01/2015 then column A = 0, otherwise leave A alone.
I have tried a few variations my latest incarnation is which obviously doesn't work.
CASE
WHEN ColB <" + Constants.StartOfYear.ToString("yyyy-MM-dd") + #"
THEN ColA = 0
END
I use lots of other CASE statement and have already selected all my columns from the table
If I uderstand you right, all you want is update some values.
If it's your case, you can use UPDATE DML:
String sql =
#"update MyTable
set ColA = 0
where ColB < #prm_ColB"; // '#' - For MS SQL, ':' for Oracle etc.
then assign value to prm_ColB and execute it like that:
// Assuming that you're working with MS SQL
using (var con = new SqlConnection(YourConnectionString)) {
con.Connect();
using (var q = new SqlCommand(con)) {
q.CommandText = sql;
// Put actual parameter value here
q.Parameters.AddWithValue("#prm_ColB", new DateTime(DateTime.Now.Year, 1, 1));
q.ExecuteNonQuery();
}
}
give your RDBMS an actual DateTime value via binding variable (#prm_ColB) do not try converting the date into string for hardcoding.

How do I get day number from a date in abap?

I need to convert a date in 'MM/DD/YYYY' format to a number that say which day in the year it is. I.E '01/01/YYYY'=1 and '12/31/YYYY'=365. Is there any built in function to do this in ABAP? I've tried googling but I couldn't find any functions which did this
Here you go in one line of code:
DATA(g_day) = p_date - CONV d( p_date(4) && '0101' ) + 1.
It is absolutely unnecessary to rely on any function module that may or may not be present in your system. Just use basic built-in language elements:
DATA: l_my_date TYPE d, " note that the data type D is YYYYMMDD
l_jan_01 TYPE d, " This will be jan 1 of the needed year
l_day TYPE i.
l_my_date = ...whatever...
l_jan_01 = l_my_date.
l_jan_01+4 = '0101'. " or any other means to get the first day of the year.
l_day = l_my_date - l_jan_01 + 1.
You can use this function module: HR_AUPBS_MONTH_DAY.
You have to pass an initial date and an end date, and it will return the number of days in between (this is what you want):
CALL FUNCTION 'HR_AUPBS_MONTH_DAY'
EXPORTING BEG_DA = P_BEGDA " Here you should put the first day of the year
END_DA = P_ENDDA " Here you put the date
IMPORTING NO_CAL_DAY = P_CAL_DAY. " This is what you want

LINQ to SQL selecting records and converting dates

I'm trying to select records from a table based on a date using Linq to SQL. Unfortunately the date is split across two tables - the Hours table has the day and the related JobTime table has the month and year in two columns.
I have the following query:
Dim qry = From h As Hour In ctx.Hours Where Convert.ToDateTime(h.day & "/" & h.JobTime.month & "/" & h.JobTime.year & " 00:00:00") > Convert.ToDateTime("01/01/2012 00:00:00")
This gives me the error "Arithmetic overflow error converting expression to data type datetime."
Looking at the SQL query in SQL server profiler, I see:
exec sp_executesql N'SELECT [t0].[JobTimeID], [t0].[day], [t0].[hours]
FROM [dbo].[tbl_pm_hours] AS [t0]
INNER JOIN [dbo].[tbl_pm_jobtimes] AS [t1] ON [t1].[JobTimeID] = [t0].[JobTimeID]
WHERE (CONVERT(DateTime,(((((CONVERT(NVarChar,[t0].[day])) + #p0) + (CONVERT(NVarChar,COALESCE([t1].[month],NULL)))) + #p1) + (CONVERT(NVarChar,COALESCE([t1].[year],NULL)))) + #p2)) > #p3',N'#p0 nvarchar(4000),#p1 nvarchar(4000),#p2 nvarchar(4000),#p3 datetime',#p0=N'/',#p1=N'/',#p2=N' 00:00:00',#p3='2012-01-31 00:00:00'
I can see that it's not passing in the date to search for correctly but I'm not sure how to correct it.
Can anyone please help?
Thanks,
Emma
The direct cause of the error may have to do with this issue.
As said there, the conversions you use are a very inefficient way to build a query. On top of that, it is inefficient because the expressions are not sargable. I.e. you are using a computed value from database columns in a comparison which disables the query analyzer to use indexes to jump to individual column values. So, you could try to fix the error by doctoring the direct cause, but I think it's better to rewrite the query in a way that only the single column values are used in comparions.
I've worked this out in C#:
var cfg = new DateTime(12,6,12);
int year = 12, month = 6, day = 13; // Try some more values here.
// Date from components > datetime value?
bool gt = (
year > cfg.Year || (
(year == cfg.Year && month > cfg.Month) || (
year == cfg.Year && month == cfg.Month && day > cfg.Day)
)
);
You see that it's not as straightforward as it may look at first, but it works. There are much more comparisons to work out, but I'm sure that the ability to use indexes will easily outweigh this.
A more straightforward, but not sargable, way is to use sortable dates, like 20120101 and compare those (as integers).