SQL Server 2008 R2 - Query from 2014 SSMS but fails from code as well.
Strange - first reference to table B works, second fails with an 'Invalid object B' error. What am I doing wrong? GO's don't help.
WITH B as (SELECT BatchOutId, SettleMerchantCode, BatchDate, BatchStatusCode, BatchTransCnt, BatchTotAmt, BatchAdjustAmt, BatchAdjustCnt
FROM MAF01
GROUP BY BatchOutId, SettleMerchantCode, BatchDate, BatchStatusCode, BatchTransCnt, BatchTotAmt, BatchAdjustAmt, BatchAdjustCnt)
SELECT * FROM B ORDER BY BatchOutId DESC
SELECT * FROM B ORDER BY BatchOutId DESC
This is as expected.
CTEs are only in scope for the next statement. They are just named queries.
You would need to either
Repeat the definition of the CTE.
Move the definition out into a view or inline function.
Materialise the results into a temp table.
Depending on what you were expecting to happen.
A cte is only valid for one query, not an entire batch. So once you do the first SELECT * FROM B, that query is finished. The next query no longer has access to the cte that the first query used.
I know this has to be duplicate
You can have multiple CTE but only one statement
The two Select are two statements
If you use a #temp then you can have more than one statement
Related
I have a query that works when I do
SELECT DISTINCT(table.field.id), 1 FROM ...
but fails when I do
SELECT 1, DISTINCT(table.field.id) FROM ...
Is this a known behavior?
Why does the first one work while the second doesn't?
Unfortunately I'm not able to add a comment yet.
What #Gordon Linoff has written is exactly right.
You are getting error as DISTINCT in general works as part of SELECT clause or AGGREGATE function. It is used to return unique rows from a result set and it can be used to force unique column values within an aggregate function.
Examples: SELECT DISTINCT * ... COUNT(DISTINCT COLUMN) or SUM(DISTINCT COLUMN).
More information's about DISTINCT in popular DB engines:
PostgreSQL:https://www.postgresql.org/docs/9.0/static/sql-select.html#SQL-DISTINCT
SQL Server: https://www.techonthenet.com/sql_server/distinct.php
Oracle: https://www.techonthenet.com/oracle/distinct.php
MySQL:
https://dev.mysql.com/doc/refman/5.7/en/distinct-optimization.html
https://dev.mysql.com/doc/refman/5.7/en/select.html
The following query was attempted to be executed when performing batch analytics with WSO2 DAS using Spark SQL. Tables 'First', 'Middle' and 'Third' are required to be combined and written to table 'All_three'.
INSERT OVERWRITE TABLE All_three
SELECT SYMBOL, VOLUME FROM First
UNION
SELECT SYMBOL, VOLUME FROM Middle
UNION
SELECT SYMBOL, VOLUME FROM Third;
Following error is displayed on WSO2 DAS when this query is executed:
ERROR: [1.79] failure: ``limit'' expected but `union' found INSERT OVERWRITE TABLE X1234_All_three SELECT SYMBOL, VOLUME FROM X1234_First UNION SELECT SYMBOL, VOLUME FROM X1234_Middle UNION SELECT SYMBOL, VOLUME FROM X1234_Third ^
Using LIMIT with UNION is not a necessity to the best of my knowledge. Enclosing the SELECT queries in parentheses too was attempted which didn't work. What am I doing wrong here? Thank you in advance!
I had the same issue.
Please make sure you had an whitespace in end of each row.
The reason is it is not considering \n as a whitespace like SSMS or other query editors.
So it reads your query without whitespace.
Hence, it read like SELECT * FROM FirstUNION not like SELECT * FROM First UNION
My issue was resolved and I hope this helps for you too.
There exists a problem with the query you mentioned here. Please change the query as below.
INSERT OVERWRITE TABLE All_three
select * from (
SELECT SYMBOL, VOLUME FROM First
UNION
SELECT SYMBOL, VOLUME FROM Middle
UNION
SELECT SYMBOL, VOLUME FROM Third
) temp;
Actually what we do here is, wrapping the union result into temporary data element called temp and select everything from there. Spark-SQL parser only takes single select element in the insert queries, and at the end of a select query it expects a limit (if available). therefore, you need to wrap the subsequent select statements into one select element. Hope this resolves your issue.
I'm trying to create a View as following:
CREATE VIEW v_MyView
AS
SET #par_count := 0; -- XXX Working in SELECT, but not in a View !? XXX
SELECT
q1.day,
q1.count_per_day,
(#par_count := #par_count + q1.count_per_day) AS count_sum -- sums up count_per_day
FROM
(SELECT
DATE(registration_date_time_obj) AS day,
COUNT(Date(registration_date_time_obj)) AS count_per_day
FROM tbl_registration_data
GROUP BY day
ORDER BY day
) AS q1
;
The select statement itself works fine, just creating a view fails in MySQL since it doesn't accept user variables/parameters within it's declaration i guess.
Is there a way to still create this view with a workaround for the parameter?
Anyways, i'm able to create a similar procedure for the select statement, but that doesn't really solve the problem since i can't call the procedure in another select statement...
Thanks for your suggestions and solutions! (:
MySQL documentation is pretty clear that variables are not allowed:
The SELECT statement cannot refer to system variables or user-defined variables.
Within a stored program, the SELECT statement cannot refer to program parameters or local variables.
You can do what you want using a correlated subquery:
SELECT DATE(registration_date_time_obj) AS day,
COUNT(Date(registration_date_time_obj)) AS count_per_day,
(SELECT COUNT(*)
FROM tbl_registration_data rd2
WHERE rd2.registration_date_time_obj <= date_add(date(rd.registration_date_time_obj), interval 1 day)
FROM tbl_registration_data rd
GROUP BY day
ORDER BY day;
Please read the documentation on VIEWS >> https://dev.mysql.com/doc/refman/5.5/en/create-view.html
A view definition is subject to the following restrictions:
The SELECT statement cannot contain a subquery in the FROM clause.
The SELECT statement cannot refer to system variables or user-defined variables.
Within a stored program, the SELECT statement cannot refer to program
parameters or local variables.
The SELECT statement cannot refer to prepared statement parameters.
Any table or view referred to in the definition must exist. After the
view has been created, it is possible to drop a table or view that
the definition refers to. In this case, use of the view results in an
error. To check a view definition for problems of this kind, use the
CHECK TABLE statement.
The definition cannot refer to a TEMPORARY table, and you cannot
create a TEMPORARY view.
You cannot associate a trigger with a view.
Aliases for column names in the SELECT statement are checked against
the maximum column length of 64 characters (not the maximum alias
length of 256 characters).
I have a problem with Aliased Columns in MySQL!
My Query:
SELECT Price AS Pr, (Pr*10/100) FROM MyTable;
MySQL WorkBench Error: UnKnown Column 'Pr' in Field List !!!
I tested my query in W3Schools with no error !
I tested my query in W3Schools with no error!
This doesn't prove that your query is valid.
You can only use aliases in GROUP BY, ORDER BY or HAVING clauses. Your usage variant is not allowed, because the value of alias is not known when MySQL is selecting the 2-nd column.
I've got a suspicion that W3Schools uses MS Access to run user queries, and MS Access does allow such atrocity as referencing column aliases in a SELECT clause that are defined in the same SELECT clause.
The standard doesn't allow this and MySQL does follow standard in this particular case.
As for solution to your problem, I can see two options.
The more generic solution, which would run in probably any SQL product, would be to use a derived table:
SELECT
Pr,
(Pr * 10 / 100) AS SomethingElse
FROM
(
SELECT
SomeComplexExpression AS Pr
FROM MyTable
) AS sub
;
The other option would be to use a variable, which is MySQL-specific:
SELECT
#Pr := SomeComplexExpression AS Pr,
(#Pr * 10 / 100) AS SomethingElse
FROM MyTable
;
Finally, if you need to test/demonstrate if something can/cannot work in MySQL, I'd recommend using SQL Fiddle.
So I have joined 3 queries together using UNIONs and want to count the number of lines in the result, but it's a bit weird. It actually works, and gives the correct answer, but it doesn't assign the "AS" part correctly.
SELECT COUNT(*) FROM (
(Long Select Statement)
UNION
(AnotherLong Select Statement)
UNION
(Even Longer Select Statement)
)
AS NoOfTweets";
The outcome is correct, but instead of assigning it to "NoOfTweets" it assigns it to "Count(*)". If I remove the "AS NoOfTweets" it stops working. If I remove some brackets it stops working. I'm running low on ideas after a long day! I can post the whole code if needs be but would rather not as it's quite long and I think that bit works.
Thanks in advance, Jack.
Edit: Fixed with:
SELECT COUNT(*) NoOfTweets FROM (
(Long Select Statement)
UNION
(AnotherLong Select Statement)
UNION
(Even Longer Select Statement)
)
AS NoOfTweets";
Thanks guys :)
You aren't putting it in the correct location. The beginning of your query should look like this:
SELECT COUNT(*) AS NoOfTweets
More on Column Alias
SELECT COUNT(*) NoOfTweets FROM
(Long Select Statement)
UNION
(AnotherLong Select Statement)
UNION
(Even Longer Select Statement)
or
SELECT COUNT(*) AS NoOfTweets FROM
(Long Select Statement)
UNION
(AnotherLong Select Statement)
UNION
(Even Longer Select Statement)
You have to use AS exactly after the item you are counting:
SELECT COUNT(*) AS `NoOfTweets`
FROM ( ... )
Also be careful with the " you have near the end. Or maybe it comes from a longer string.
The error is Every derived table must have its own alias which is something I didn't know, so thanks for the education :)
http://sqlfiddle.com/#!9/d30f4/4
Nice of MySQL to give an explanation - I tried with MS SQL on SQLFiddle and just got Incorrect syntax near ')'. which isn't so helpful!
So, your 'NoOfTweets' is the name given to the results column, and also to the 'derived table' which is required by the SQL engine but could be a different name ... it's not returned in the results. The point of naming a derived table is in case you wish to JOIN to other tables and reference the fields in the joins.