I'm trying to pass more than one variable to an sqlite query in Racket.
(define select-test
(prepare dbconn "SELECT count(*) FROM All_data WHERE Season = ? AND Division = '?'"))
(define season 2019)
(define league "E0")
;(query-value dbconn select-test '(season league))
;(query-value dbconn select-test season league)
There are examples online showing both a list and separate variables as input to a query, but neither of these are working for me.
I either get this message for the list:
query-value: cannot convert given value to SQL type
given: '(season league)
type: parameter
dialect: SQLite
or 'wrong number of parameters for query' if done separately.
Can someone please help with the correct syntax?
The problem is in your SQL. This statement:
SELECT count(*) FROM All_data WHERE Season = ? AND Division = '?'
has one parameter (for the Season comparison). The '?' is just a literal string containing a question mark. Just write ? instead, like this:
SELECT count(*) FROM All_data WHERE Season = ? AND Division = ?
Then call it with two arguments, like this:
(query-value dbconn select-test season league)
By the way, you can double-check the number of parameters the prepared statement has with
(length (prepared-statement-parameter-types select-test))
With SQLite, there isn't any information in the types themselves, but the length tells you the number of parameters.
Related
I have a requirement where the current type is NUMERIC but I need it to be DATETIME, I am currently working with the data owner to get them to convert the data type so I will not have to perform these steps.
As stated above, the NUMERIC type needs to be changed to DATETIME but I have an issue where zero values exist. I have currently written two SQL queries to achieve the result but I was hoping to be able to do this in a single query.
See the below two queries:
Query 1
SELECT
MATERIAL,DESC,NUMBER,
CASE
WHEN START_ACTUAL = 0 THEN NULL
ELSE START_ACTUAL
END AS START_ACTUAL,
CASE
WHEN END_ACTUAL = 0 THEN NULL
ELSE END_ACTUAL
END AS END_ACTUAL,
FROM `SAMPLEFILE1`
Query 2
SELECT
MATERIAL,DESC,NUMBER,
PARSE_DATETIME('%Y%m%d%H%M%S', CAST(START_ACTUAL AS STRING)) AS START_ACTUAL,
PARSE_DATETIME('%Y%m%d%H%M%S', CAST(END_ACTUAL AS STRING)) AS END_ACTUAL,
FROM `SAMPLEFILE1_VIEW`
I'm sure someone will put me right straightaway and it is very simple :)
Thanks in advance
You could wrap your case statements in the CAST and PARSE_DATETIME, but you could just use nullif:
SELECT
MATERIAL,DESC,NUMBER,
PARSE_DATETIME('%Y%m%d%H%M%S', CAST(NULLIF(START_ACTUAL,0) AS STRING)) AS START_ACTUAL,
PARSE_DATETIME('%Y%m%d%H%M%S', CAST(NULLIF(END_ACTUAL,0) AS STRING)) AS END_ACTUAL,
FROM `SAMPLEFILE1_VIEW`
Can anybody please guide me in writing this below SQL in U-SQL language used in Azure Data Lake
select tt.userId, count(tt.userId) from (SELECT userId,count(userId) as cou
FROM [dbo].[users]
where createdTime> DATEADD(wk,-1,GETDATE())
group by userId,DATEPART(minute,createdTime)/5) tt group by tt.userId
I don't find the DATEPART function in U-SQL . Azure Data Analytic job is giving me error.
U-SQL does not provide T-SQL intrinsic functions except for a few (like LIKE). See https://msdn.microsoft.com/en-us/library/azure/mt621343.aspx for a list.
So how do you do DateTime operations? You just use the C# functions and methods!
So DATEADD(wk, -1, GETDATE()) is something like DateTime.Now.AddDays(-7)
and
DATEPART(minute,createdTime)/5 (there is an extra ) in your line) is something like createdTime.Minute/5 (maybe you need to cast it to a double if you want non-integer value).
For anybody who is looking for the implementation mentioned by Michael. It's like below
#records =
EXTRACT userId string,
createdTime DateTime
FROM "/datalake/input/data.tsv"
USING Extractors.Tsv();
#result =
SELECT
userId,
COUNT(createdTime) AS userCount
FROM #records
WHERE createdTime > DateTime.Now.AddDays(-30)
GROUP BY userId,createdTime.Minute/5;
#result2= SELECT userId,COUNT(userId) AS TotalCount
FROM #result
GROUP BY userId;
OUTPUT #result2
TO "/datalake/output/data.csv"
USING Outputters.Csv();
I am creating an SQL db and trying to iterate over an excel file and put all the data in to the SQL table as follows but I keep getting an annoying error. I have looked at the data types and still can't get my head around it please let me know if anyone spots what the problem is my code is:
import sqlite3
from openpyxl import load_workbook
#wb = load_workbook(r"LeaguePlayers.xlsx")
#read workbook to get data
wb = load_workbook(filename = r"LeaguePlayers.xlsx", use_iterators = True)
ws = wb.get_sheet_by_name(name = 'Sheet1')
#ws = wb.worksheets
conn = sqlite3.connect("players.db") # or use :memory: to put it in RAM
cursor = conn.cursor()
# create a table
cursor.execute("""CREATE TABLE players
(player TEXT,
team TEXT,
points INTEGER,
cost REAL,
position TEXT)
""")
#Iterate through worksheet and print cell contents
for row in ws.iter_rows():
for cell in row:
cursor.execute("INSERT INTO players VALUES (?,?,?,?,?)", row)
conn.commit()
#----------------------------------------
# display SQL data
#----------------------------------------
c.execute('SELECT * FROM players')
for row in c:
print (row)
The error i get says:
cursor.execute("INSERT INTO players VALUES (?,?,?,?,?)", row)
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
I really think you need to do some kind of introduction to Python.
You are making two elementary mistakes: looping of the cells in a row but passing the row to the query; passing a complex object as opposed to a native Python type such as an integer or string.
Something like the following is what you want:
player = [cell.value for cell in row]
cursor.execute(query, player)
Note, that execute takes a sequence (tuple or list) as the second argument.
i am bit confused by the nature and working of query , I tried to access database which contains each name more than once having same EMPid so when i accessed it in my DROP DOWN LIST then same repetition was in there too so i tried to remove repetition by putting DISTINCT in query but that didn't work but later i modified it another way and that worked but WHY THAT WORKED, I DON'T UNDERSTAND ?
QUERY THAT DIDN'T WORK
var names = (from n in DataContext.EmployeeAtds select n).Distinct();
QUERY THAT WORKED of which i don't know how ?
var names = (from n in DataContext.EmployeeAtds select new {n.EmplID, n.EmplName}).Distinct();
why 2nd worked exactly like i wanted (picking each name 1 time)
i'm using mvc 3 and linq to sql and i am newbie.
Both queries are different. I am explaining you both query in SQL that will help you in understanding both queries.
Your first query is:
var names = (from n in DataContext.EmployeeAtds select n).Distinct();
SQL:-
SELECT DISTINCT [t0].[EmplID], [t0].[EmplName], [t0].[Dept]
FROM [EmployeeAtd] AS [t0]
Your second query is:
(from n in EmployeeAtds select new {n.EmplID, n.EmplName}).Distinct()
SQL:-
SELECT DISTINCT [t0].[EmplID], [t0].[EmplName] FROM [EmployeeAtd] AS
[t0]
Now you can see SQL query for both queries. First query is showing that you are implementing Distinct on all columns of table but in second query you are implementing distinct only on required columns so it is giving you desired result.
As per Scott Allen's Explanation
var names = (from n in DataContext.EmployeeAtds select n).Distinct();
The docs for Distinct are clear – the method uses the default equality comparer to test for equality, and the default comparer sees 4 distinct object references. One way to get around this would be to use the overloaded version of Distinct that accepts a custom IEqualityComparer.
var names = (from n in DataContext.EmployeeAtds select new {n.EmplID, n.EmplName}).Distinct();
Turns out the C# compiler overrides Equals and GetHashCode for anonymous types. The implementation of the two overridden methods uses all the public properties on the type to compute an object's hash code and test for equality. If two objects of the same anonymous type have all the same values for their properties – the objects are equal. This is a safe strategy since anonymously typed objects are essentially immutable (all the properties are read-only).
Try this:
var names = DataContext.EmployeeAtds.Select(x => x.EmplName).Distinct().ToList();
Update:
var names = DataContext.EmployeeAtds
.GroupBy(x => x.EmplID)
.Select(g => new { EmplID = g.Key, EmplName = g.FirstOrDefault().EmplName })
.ToList();
I am having a bit of a difficult time figuring out how accomplish a task outlined in my question header.
Basically, I have a list of 'News' objects defined as:
Dim news_list As List(Of News) = myNamespcae.News.ListNews()
Depending on a condition, I have another 'News' object list as;
Dim news_headlines As List(Of News) = myNamespace.News.getHeadlines()
Then, I have 'spots' again as List(of News) as;
Dim spots = (From n In news_list Take (10) Select n)
I am trying to accomplish;
if news_headlines is not empty,if any news_headlines News object exists in spots, remove it from spots. return filtered spots.
Any guidance will be appreciated..
Thanks.
If you want to pick ten from Spots and then filter out the ones in news_headlines, it would be something like this (warning: LINQ syntax in VB entirely from memory):
Dim spots1 = (From n In news_list Take (10) Select n)
Dim spots2 = (From n in spots1 Where Not news_headlines.Contains(n) Select n)
If you want to filter out the ones in news_headlines and then pick ten, it would be something like this:
Dim spots1 = (From n In news_list Where Not news_headlines.Contains(n) Select n)
Dim spots2 = (From n in spots1 Take (10) select n)
You can of course combine the two queries. Note that I'm assuming news_headlines is not null. I'm also assuming that your news items are either the same object instances or implement IEquatable<T>.
I think there are similar questions in stackoverflow. Anyway, you can possibly use "Intersect" to get the elements that are both in the spots and the headlines and remove them from the spots list.
The code should be trivial but I haven't used VB.net in a while, sorry.