Subquery with alias in SQLite - sqlite

I have a query that I run in PostgreSQL like this:
select
c_count, count(*) as custdist
from (
select
c_custkey,
count(o_orderkey)
from
customer left outer join orders on
c_custkey = o_custkey
and o_comment not like '%special%requests%'
group by
c_custkey
)as c_orders (c_custkey, c_count)
group by
c_count
order by
custdist desc,
c_count desc;
And I wanted to run it on SQLite, but I got this error: Error: near" (": syntax error. Maybe he doesn't recognize this as c_orders (c_custkey, c_count).
Is there any way to rewrite this query to execute in SQLite?

SQLite does not allow redefining/renaming columns for an nested, aliased query. You can do that with a WITH clause (i.e. Common Table Expression; CTE). Or you can add aliases to the nested query columns directly using AS keyword.
Interesting that this is exactly how the outer query columns are named. Just use the same pattern for the nested query. I don't use PostgreSQL, but why not add aliases directly on each column and complicate it by using different syntax for each part of the query?
select
c_count, count(*) as custdist
from (
select
c_custkey,
count(o_orderkey) AS c_count
from
customer left outer join orders on
c_custkey = o_custkey
and o_comment not like '%special%requests%'
group by
c_custkey
) AS c_orders
group by
c_count
order by
custdist desc,
c_count desc;

Related

maraidb CTE, how to reuse selected order?

I haev a query where I have a CTE that selects some rows in a specfic order, and I want to use that same order for my main data set Im returning:
WITH selector (id) AS (SELECT id FROM ..... ORDER BY something)
SELECT ...
FROM users u
JOIN selector s ON s.id = u.id
ORDER BY FIELD(u.id, (SELECT id FROM selector))
but this isn't valid syntax in the last ORDER BY FIELD statement as the sub query returns more than one row, is it possible to achieve something like this?
The function FIELD() needs a list of values and not the results of a query.
You can use the function GROUP_CONCAT() to create a comma separated list of ids returned by the CTE, ordered by your conditions and then the function FIND_IN_SET() to join the CTE to the table and sort by its result:
WITH selector (ids) AS (SELECT GROUP_CONCAT(id ORDER BY something) FROM .....)
SELECT ...
FROM users u INNER JOIN selector s
ON FIND_IN_SET(u.id, s.ids)
ORDER BY FIND_IN_SET(u.id, s.ids)
Or, use ROW_NUMBER() window function:
WITH selector (id, rn) AS (SELECT id, ROW_NUMBER() OVER (ORDER BY something) FROM .....)
SELECT ...
FROM users u INNER JOIN selector s
ON s.id = u.id
ORDER BY s.rn

Two queries in one statment

I want in put two queries in one statement how can i do that in this state?
1
stmt = `SELECT Comments.*, Users.username,Users.avatar from Users
INNER JOIN Comments ON Comments.users_id =Users.users_id
WHERE Comments.post_id= 1`
2
`SELECT COUNT(*) comment FROM Comments WHERE Comments.post_id= 1`;
Cross join the 1st query to the 2nd:
SELECT c.*, u.username, u.avatar, t.counter
FROM Users u INNER JOIN Comments c
ON c.users_id = u.users_id
CROSS JOIN (SELECT COUNT(*) counter FROM Comments WHERE post_id = 1) t
WHERE c.post_id = 1
I don't know much about SQLite, but in SQL Server you can use ";" to use multiple queries.
Maybe it does work for SQLite.
You can use GROUP BY on comments table in a way:
'SELECT COUNT(Comments.<id>), Comments.*, Users.username,Users.avatar
from Users INNER JOIN Comments ON Comments.users_id =Users.users_id
WHERE Comments.post_id = 1 GROUP BY Comments.<id>';
*This syntax of GROUP BY clause follows PostgreSQL. You might need to tweak according to the syntax followed by sqlite.

How to reuse a table with UNION?

I am trying to reuse a table in SQLite. My attempt is as follows:
SELECT
Partials.e_sentence
FROM
(SELECT
e_sentence, _id
FROM
Pair
JOIN PairCategories
ON
_id=PairId AND CategoryId=53
UNION
SELECT
e_sentence, _id
FROM
Pair
WHERE
e_sentence LIKE '%' || 'how often' || '%'
GROUP BY
e_sentence)
AS Parents JOIN Partials
ON Parents._id=ParentId
UNION
SELECT
e_sentence
FROM
Parents
The key part I am trying to accomplish is at the bottom, where I try to UNION a table created in the previous statement. Is there a way to do this in SQLite, or am I forced to repeat the query that made the Parents table in the first half of the UNION?
In SQLite 3.8.3 or later, you can use a common table expression:
WITH Parents AS (
SELECT e_sentence, _id
FROM Pair
JOIN PairCategories
...
)
SELECT Partials.e_sentence
FROM Parents
JOIN Partials ON Parents._id = ParentId
UNION
SELECT e_sentence
FROM Parents;
If you're using an older SQLite (probably because you're using an older Android), you can create a view for the subquery:
CREATE VIEW Parents AS
SELECT e_sentence, _id
FROM Pair
JOIN PairCategories
...;
SELECT Partials.e_sentence
FROM Parents
JOIN Partials ON Parents._id = ParentId
UNION
SELECT e_sentence
FROM Parents;
If you do not want to have this view permanently in the database, you could make it temporary (CREATE TEMPORARY VIEW ...) so that it is not available outside the current database connection, or, as last resort, you could just insert the subquery wherever you would use Parent:
SELECT Partials.e_sentence
FROM (SELECT ...) AS Parents
JOIN Partials ON Parents._id = ParentId
UNION
SELECT e_sentence
FROM (SELECT ...) AS Parents;

Is it possible to use WHERE clause in same query as PARTITION BY?

I need to write SQL that keeps only the minimum 5 records per each identifiable record in a table. For this, I use partition by and delete all records where the value returned is greater than 5. When I attempt to use the WHERE clause in the same query as the partition by statement, I get the error "Ordered Analytical Functions not allowed in WHERE Clause". So, in order to get it to work, I have to use three subqueries. My SQL looks ilke this:
delete mydb.mytable where (field1,field2) in
(
select field1,field2 from
(
select field1,field2,
Rank() over
(
partition BY field1
order by field1,field2
) n
from mydb.mytable
) x
where n > 5
)
The innermost subquery just returns the raw data. Since I can't use WHERE there, I wrapped it with a subquery, the purpose of which is to 1) use WHERE to get records greater than 5 in rank and 2) select only field1 and field2. The reason why I select only those two fields is so that I can use the IN statement for deleting those records in the outermost query.
It works, but it appears a bit cumbersome. I'd like to consolidate the inner two subqueries into a single subquery. Is this possible?
Sounds like you need to use the QUALIFY clause which is the HAVING clause for Window Aggregate functions. Below is my take on what you are trying to accomplish.
Please do not run this SQL directly against your production data without first testing it.
/* Physical Delete */
DELETE TGT
FROM MyDB.MyTable TGT
INNER JOIN
(SELECT Field1
, Field2
FROM MyDB.MyTable
QUALIFY ROW_NUMBER() (PARTITION BY Field1, ORDER BY Field1,2)
> 5
) SRC
ON TGT.Field1 = SRC.Field1
AND TGT.Field2 = SRC.Fileld2
/* Logical Delete */
UPDATE TGT
FROM MyDB.MyTable TGT
,
(SELECT Field1
, Field2
FROM MyDB.MyTable
QUALIFY ROW_NUMBER() (PARTITION BY Field1, ORDER BY Field1,2)
> 5
) SRC
SET Deleted = 'Y'
/* RecordExpireDate = Date - 1 */
WHERE TGT.Field1 = SRC.Field1
AND TGT.Field2 = SRC.Fileld2

Multiple query from multiple tables in sqlite

I am using it but no value i found...I think there is mistake in this query....Actually I want to know how to use multiple sum, multiplication etc using mutiple tables in sqlite
SELECT
dhid, dprice, dname,
SUM(dmilk) AS totalmilk,
dprice*SUM(dmilk) AS totalmilkamt,
SUM(ghee) AS toalghee,
SUM(ghee*gheeprice) AS totalgheeamt,
SUM(ghee*gheeprice)+dprice*SUM(dmilk) AS totals,
SUM(cashamount) AS totalcash,
SUM(ghee*gheeprice)+dprice*SUM(dmilk)-SUM(cashamount) AS balance
FROM
( SELECT *
FROM costumer
LEFT OUTER JOIN salesdata
ON costumer.dhid=salesdata.ddhid
LEFT OUTER JOIN cashdata
ON salesdata.ddhid=cashdata.uid
AND utype='costumer')
WHERE dmonth='$mikdatem'
AND dyear='$mikdatey'
AND dhid='$dhid'
ORDER BY dhid ASC
Your select above will not help us because we don't have the underlying data to get an idea what you wish to do.
So the generalistic answer is this:
when using grouping-functions (SUM/COUNT...) you always require some form of "GROUP BY" to columns not used in those group-functions.
Example given:
SELECT name, sum(dmilk)
FROM milk_entry
GROUP BY name

Resources