group_concat sqlite and order by - sqlite

I am trying to order within group_concat in sqlite3. This is not supported in the way that it is for mysql, so I CAN NOT do this:
group_concat(logID order by logDateTime DESC)
My full query is here, I need logID to be ordered by logDateTime. I read about a subquery method here: Sqlite group_concat ordering but I was unable to get it to work in my query.
SELECT logID,
NULL AS sessionID,
logDateTime,
NULL AS sessionName,
NULL AS NamesInRandomOrder
FROM logs
WHERE sessionID IS NULL
UNION ALL
SELECT NULL,
sessions.sessionID,
MAX(logDateTime),
sessions.sessionName,
group_concat(logID)
FROM logs
JOIN sessions ON logs.sessionID = sessions.sessionID
GROUP BY sessions.sessionID
ORDER BY 3 DESC

This orders the subquery, but SQLite doesn't guarantee that the order remains in all cases:
SELECT logID,
NULL AS sessionID,
logDateTime,
logName,
NULL AS NamesInRandomOrder
FROM logs
WHERE sessionID IS NULL
UNION ALL
SELECT NULL,
sessionID,
MAX(logDateTime),
sessionName,
group_concat(logName)
FROM (SELECT sessions.sessionID AS sessionID,
logDateTime,
sessionName,
logName
FROM logs JOIN sessions ON logs.sessionID = sessions.sessionID
ORDER BY sessions.sessionID,
logName)
GROUP BY sessionID
ORDER BY 3 DESC

Related

SOQL Query with a Subquery that uses GROUP BY and HAVING throws unknown error

I'm trying to query a list of records from a custom object (SB_User__c) where the value in the Email__c field is not unique.
The following query captures the entire table as expected:
SELECT Id, Name, Email__c, External_Id__c
FROM SB_User__c
ORDER BY Email__c, Name
And my subquery returns a list of Email__c values that are not unique:
SELECT Email__c
FROM SB_User__c
GROUP BY Email__c
HAVING COUNT(Id) > 1
But when these queries are combined, I receive an unknown error:
SELECT Id, Name, Email__c, External_Id__c
FROM SB_User__c
WHERE Email__c IN (
SELECT Email__c FROM SB_User__c
GROUP BY Email__c
HAVING COUNT(Id) > 1)
ORDER BY Email__c, Name
Is there a way to accomplish what I'm trying to without involving apex?
i think the problem is probably in the having clause, i already run a similar query with this editor online:
online editor for sql queries
SELECT * FROM Customers
WHERE CustomerID IN (
SELECT CustomerID FROM Customers
GROUP BY CustomerID
HAVING CustomerID > 50)
ORDER BY Country ASC, CustomerName DESC;
and this query runs just ok, you can check the having clause.

The default schema does not exist. error when executing stored procedure

Create stored procedure
CREATE PROCEDURE dbo.GetBookList
-- Add the parameters for the stored procedure here
AS
BEGIN
create table BookAuthersName
(
BookId int,
Names varchar(255)
);
insert into BookAthersName(BookId,Names)
select
t1.BookId,
stuff((select ', '+a.Name
from BookAuthers t2 join Authers a on t2.AutherId= a.Id where t1.BookId = t2.BookId
for xml path('')),
1,2,'') [Values]
from dbo.BookAuthers t1
group by t1.BookId
create table BookSubjectNames
(
BookTypeId int,
Names varchar(255)
);
insert into BookSubjectNames(BookTypeId,Names)
select
t1.BookTypeId,
stuff((select ', '+a.Name
from BookTypeSubjects t2 join Subjects a on t2.SubjectId= a.Id where t1.BookTypeId = t2.BookTypeId
for xml path('')),
1,2,'') [Values]
from dbo.BookTypeSubjects t1
group by t1.BookTypeId
SELECT dbo.BooksType.Name, dbo.BooksType.BuyingDate AS [Buying Date], dbo.Publishers.Name AS [Publisher Name], dbo.Inventory.TotalBooks AS [Total Books],
dbo.Inventory.TotalIssuedBooks AS [Total Issued Books], ban.Names as [Auther Names] ,bsn.Names as [Subject Names]
FROM dbo.BooksType INNER JOIN dbo.Inventory
ON dbo.BooksType.Id = dbo.Inventory.BookTypeId
INNER JOIN dbo.Publishers ON dbo.BooksType.PublisherId = dbo.Publishers.Id
inner join BookAuthersName ban on dbo.BooksType.Id = ban .BookId
inner join BookSubjectNames bsn on dbo.BooksType.Id = bsn .BookTypeId
drop table BookAuthersName
drop table BookSubjectNames
END
It gives error when executing through a .net website. Error is
The default schema does not exist. error when executing stored
procedure.
Gone through some solutions but none seems to help
I am using Integrated Security=True in webconfig connection string
First thing you must get schema name with query
select schema_name()
If the schema name is null you must try set default name with query
ALTER USER [dbo.database_name] WITH DEFAULT_SCHEMA = [dbo];

DELETE from a Join in SQLite / syntax for IN clause on tuples?

I have a schema which uses a compound primary key to store users and associated data, like so:
CREATE TABLE users (
domain integer,
userid integer,
...
PRIMARY KEY (domain, userid)
);
CREATE TABLE userdata (
domain integer,
userid integer,
key integer,
...
PRIMARY KEY (domain, userid, key),
FOREIGN KEY (domain, userid) REFERENCES users(domain, userid)
);
I cannot make changes to this schema, nor can I opt to use another DBMS.
I want to delete some rows in userdata, based on a criterion over users. Conceptually, i'd like to do something like:
DELETE FROM userdata
WHERE (domain, userid) IN (
SELECT domain, userid FROM users WHERE <some condition>
) AND key = some_constant;
Or alternatively
DELETE ud FROM userdata ud
INNER JOIN users u on u.domain = ud.domain and u.userid = ud.userid
WHERE <some condition over u>
AND ud.key = some_constant
But sqlite3 (3.8.2) rejects both forms, the former with
Error: near ",": syntax error
and the latter with
Error: near "ud": syntax error
Annoyingly, the IN syntax works perfectly well when the join key consists of a single column.
What is the proper syntax or technique for achieving this ?
Not a SQLite user but I'd try selecting the ROWIDs to delete in userdata. I mean something like
delete from userdata
where rowid in (
select ud.rowid
from userdata ud
join users u on ...
where condition
)
I am supposing you want to delete key from user_data and x,y,z condition on user.
DELETE ud.key FROM user_data AS ud
LEFT JOIN users AS u ON ud.user_id = u.user_id
WHERE u.something='condition'
Your first attempt does not work because tuples (or whatever they are called) are not supported by SQLite (supported syntax here).
Your second attempt is invalid syntax as there is no JOIN in DELETE statements (maybe as an extension introduced by some DBMS but not in SQL92 apparently).
What you can try instead is:
DELETE FROM userdata
WHERE domain IN (SELECT u.domain FROM users u WHERE <some condition>)
AND userid IN (SELECT u.userid FROM users u WHERE <some condition> AND domain = u.domain)
AND key = some_constant;

SQL Server : Declare is causing problems in query

I currently have an issue with SQL Server which I can't figure out.
The error is:
A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations
SQL:
DECLARE #IdUser INT
Select
#IdUser = Id,
Username,
(Select Count(*) From GagsLikes where Userid = #IdUser And Good = 1) as GagLikes,
(Select Count(*) From GagsViews where UserID = #IdUser),
(Select Count(*) From Gags Where UserID = #IdUser) as GagViews
From
Users
Order by
GagLikes, GagViews
Thanks in advance!
You may not use that variable as you do it try this:
Select
U.Id,
U.Username,
(Select Count(*) From GagsLikes where Userid = U.Id And Good = 1) as GagLikes,
(Select Count(*) From GagsViews where UserID = U.Id),
(Select Count(*) From Gags Where UserID = U.Id) as GagViews
From
Users AS U
Order by
GagLikes, GagViews
your table might return more then one rows . make sure that your table return only one row otherwise it can
t store multiple id's in to one int variable .

SQL Server: How to select multiple columns with 1 column being distinct?

I am trying to do an SQL query on two tables to retrieve multiple columns with a certain column (PostID) to be distinct (and it is not the primary key of the that table).
In addition, I need the selected distinct rows to be the latest (one of the columns retrieved is the entry date).
Detailed description:
I am building a forum like application, using 3 tables to store data.
I use table1 to store user details, table2 to store the meta data for posts, table3 to store the post details, updates, and replies (postID is unique in table2 pointing towards an original post, while in table3, it is used to show the original post and updates and replies).
Table columns:
table1 (UserID, FullName, mobile, etc.)
table2 (postID, UserID, EntryDate, Deleted columns)
table3 (postdetailsId, PostID, UserID, Entrydate, etc.)
I am trying to retrieve all the posts for 1 user in a gridview, my SQL query uses the USERID to retrieve all his posts from the table. However, it is retrieving the original post and all its updates, and I only want to retrieve the latest update of each post.
How can it be done fully in SQL (I know I can do it in C# with the returned results)?
My query:
SELECT T1.FullName, T3.PostID, T3.EntryDate, T3.Title
FROM Table1 as T1, Table3 as T3
WHERE T3.UserID = T1.UserID
AND T3.UserID = #UserID
You could use GROUP BY PostID along with MAX(EntryDate)
SELECT *
FROM (
SELECT posts.*, ROW_NUMBER() OVER (PARTITION BY post_updates.UserID, post_updates.PostID ORDER BY post_updates.EntryDate DESC) AS rn
FROM table1 users
JOIN table3 post_updates
ON post_updates.userID = users.UserID
WHERE users.UserID = #UserID
) q
WHERE rn = 1

Resources