In a SQLite3 database, I have a table "projects" which id field is composed the following way:
[user id]_[user's project id]
For example, with user id=45, here is some data:
45_1
45_10
45_102
45_2
45_3
45_4
45_68
45_9
I need to get the max of the project id, which is the number after the '_' delimiter (which is 102 in the example). How can I achieve that?
Thank you in advance.
SELECT max(cast((substr(id, pos + 1) AS integer)) AS project_id
FROM (SELECT *, instr(id,'_') AS pos FROM projects);
select max(cast(replace(id, "45_", "") as integer)) from projects;
Now, I should point out this is not making very good use of SQL. Why not have two fields, so you could have proper foreign keys? It would make your life a lot easier
Second, if you don't only have project id = 45, you will need to use the CONCAT function. But I'm hoping you can figure that part out on your own with the functions above.
Related
Julia, SQLite3
Hi! I have an SQLite3 database and want to get information from it into a string, not DataFrame.
# Connection to database
db = SQLite.DB(raw"pictures.sqlite")
# Creation of table
SQLite.execute(db, "DROP TABLE IF EXISTS Files")
SQLite.execute(db, "CREATE TABLE IF NOT EXISTS Files
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
FullName TEXT,
creation_date TEXT,
change_date TEXT,
size INTEGER,
UNIQUE (ID))")
#Another code
#This is a way to add rows to database (it works)
DBInterface.execute(db,
"INSERT INTO Files (FullName, creation_date, change_date, size)
VALUES
('$fileName', '$cdate', '$mdate', '$fileSize')
")
#Then i am trying to get one row into a string
strq = SQLite.DBInterface.execute(db, "SELECT * FROM Files WHERE ID=3")
#I can't transfornm these to string
I'm writing on Julia and need help!!
TLDR:
CSV.write(stdout, strq);
Explanation
The API of SQLite.jl assumes using DBInterface.execute for querying the database.
This method yields an object of type SQLite.Query.
Let's have a look what can we do with it:
julia> methodswith(SQLite.Query, supertypes=true)
[1] eltype(q::SQLite.Query) in SQLite at ~/.julia/packages/SQLite/wpQeE/src/tables.jl:51
[2] isempty(q::SQLite.Query) in SQLite at ~/.julia/packages/SQLite/wpQeE/src/tables.jl:15
[3] iterate(q::SQLite.Query) in SQLite at ~/.julia/packages/SQLite/wpQeE/src/tables.jl:94
[4] iterate(q::SQLite.Query, rownumber) in SQLite at ~/.julia/packages/SQLite/wpQeE/src/tables.jl:100
You can see one important thing - you can do whatever you want with SQLite.Query as long as it matches the Tables.jl interfaces. So you are not obliged to use DataFrames but there is no "pure string" implementation, such thing would not make any sense neither.
However, there are many interfaces for Tables. The one you need is CSV.jl will exactly give you something like "string representation" of your SQL table.
Try this with your code (I inserted one row to my table to see the results):
julia> CSV.write(stdout, strq);
ID,FullName,creation_date,change_date,size
1,somefilename,somecdate,somemfate,0
I'm using the RODBC package inside an ORACLE DATA BASE (DB). Everything is doing very well, but I need to obtain a table from this DB and some variables as character type, not numbers.
So, I made my query like this:
e ManzResul_VIII<-sqlQuery(con,"select distinct t.fono_id_dis,
t.id_predio,
t.co_calle,
t.nu_casa,
t.x,
t.y,
t.plancheta from c_araya.proy_dist08_todo t where nvl(t.fono_tipo_dis, '-') not in ('CLIENTE', 'POTENCIAL', 'CARTERA') and nvl(t.x, 0) <> 0 ")
Is impossible to get the ID number as Character, this query change the type of my iDs variables from Character to Numeric type (The ID has a zero at the beginning, but has been changed it into a number). I have read the function description, but I can see how to manage it.
Any idea would be really appreciated, thanks in advance!
Change the query to cast the id to the data type you want:
select distinct cast(t.fono_id_dis as varchar(255)) as id
. . .
This should work with most databases.
This works for me:
library(RODBC)
con <- odbcDriverConnect('driver={SQL Server};server=[your server name];database=[your database name];trusted_connection=true')
ManzResul_VIII<-sqlQuery(con,"select distinct ('m' + id) as id from [your table]")
I have been looking all day for a solution that works for my situation. I have found some things that are very similar but don't work for my situation, I tried them.
Here is the scenario; I have two table base and partdetails. I have an asp website (internal ONLY) that has drop down lists to select the parameters for a SQL query that fills a data grid view.
My problem is this, I need to be able, based on the drop down list boxes on the page, assign the column name that the criteria that is entered to be searched for.
Here is the query that I am trying to define: (This one returns 0 rows)
sqlCmd.CommandText = ("Select ba.referenceid, ba.partnum, pd.width, pd.length, CONVERT(varchar(12), pd.dateentered, 101) As [dateentered], ba.partqty, ba.status, ba.material From tbl_dlbase ba Join tbl_partdetails pd On ba.referenceid = pd.referenceid Where Case #field1 When 'part #' Then 'ba.partnum' When 'Spacing' Then 'pd.spacing' When 'Surface' Then 'pd.surface' When 'Height' Then 'pd.height' When 'Thickness' Then 'pd.thickness' End Like '%' + #criteria1 + '%'")
sqlCmd.Parameters.AddWithValue("#field1", ddlSc1.SelectedItem.Text)
sqlCmd.Parameters.AddWithValue("#criteria1", txbCriteria1.Text)
This is the latest version of the SQL statement that I have tried. I need to be able to set the field/column name based on the selection from the drop down list ddlsc1 on the asp page.
I have also been trying the queries in Studio manager to see if maybe I have fat fingered something but it also returns 0 rows so I know something is wrong with the query.
So how can I set the column name field using a parameter for the name. I know this is a huge security concern with SQL injection but this is an internal only site, and more importantly my boss said he wants it done with variables.
I don't really see a problem with this other than you have single quotes around your THEN values. Does this fix it?
SELECT ba.referenceid
,ba.partnum
,pd.width
,pd.length
,CONVERT(VARCHAR(12), pd.dateentered, 101) AS [dateentered]
,ba.partqty
,ba.STATUS
,ba.material
FROM tbl_dlbase ba
JOIN tbl_partdetails pd ON ba.referenceid = pd.referenceid
WHERE CASE #field1
WHEN 'part #'
THEN ba.partnum
WHEN 'Spacing'
THEN pd.spacing
WHEN 'Surface'
THEN pd.surface
WHEN 'Height'
THEN pd.height
WHEN 'Thickness'
THEN pd.thickness
END LIKE '%' + #criteria1 + '%'
I am pretty sure you guys have a simple and fast solution to my problem but my SQL-Skills are limited and I can't figure it out by my self.
So what I have is something like:
Newsgroup: [Name(PK)]
Article: [Id(PK)] [newsgroupName (FK)] [date:Date] [read:Boolean]
What I want know is a query that gives me the Name of each Newsgroup along with the Count of unread articles, Count of all articles and the date of the most recent one...
Is this even possible to archieve in a single Select-Query?
Thank you guys in advance!
You can simply use the appropriate aggregation functions:
SELECT newsgroupName,
SUM(NOT read) AS countUnread,
COUNT(*) AS countAll,
MAX(date) AS mostRecentDate
FROM Article
GROUP BY newsgroupName;
I guess something like this:
SELECT name, COUNT(countUnread) AS countUnread, COUNT(countRead) AS countRead, MAX(mostRecentDateUnread) AS mostRecentDateUnread, MAX(mostRecentDateRead) AS mostRecentDateRead FROM (
SELECT newsgroupName AS name, COUNT(newsgroupName) AS countUnread, 0 AS countRead, MAX(date) AS mostRecentDateUnread, NULL AS mostRecentDateRead
FROM Article
WHERE read = 0
GROUP BY newsgroupName, read
UNION ALL
SELECT newsgroupName AS name, 0 AS countUnread, COUNT(newsgroupName) AS countRead, NULL AS mostRecentDateUnread, MAX(date) AS mostRecentDateRead
FROM Article
WHERE read = 1
GROUP BY newsgroupName, read
)
GROUP BY name
I haven't tried but in theory with some fix it could work.
Kindly review this simple SQLite-fiddle .
If any word in the column ITEM of table TWO matches any word in the column NAME_2 of table ONE, there should be a result(s).
Tried many permutes, yet not sure how to form the query for achieving this. Should the GLOBclause be used instead of LIKE, or perhaps some other wildcard patterns?
Many thanks in advance!
As per my comment, I think you can make use of instr as well. For example:
SELECT * FROM Table1 T1, Table2 T2 where instr(T2.NAME_2,T1.ITEM);
The above should return rows where T2.NAME contains a string = T1.ITEM