Two select statments with union not working - mysql

i am trying to implement following query,
(SELECT
MAX(final_avg_total.`Provider Name`) AS `Hospital Name`,
final_avg_total.`DRG Definition`,
final_avg_total.`Provider Id`,
SUM(final_avg_total.avg_total_payments) AS avg_payments,
SUM(final_avg_total.avg_covered_charges) AS avg_covered,
(SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments)) / SUM(final_avg_total.avg_covered_charges) AS total_average,
1 - (SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments)) / SUM(final_avg_total.avg_covered_charges) AS total_percentage
FROM final_avg_total
GROUP BY final_avg_total.`Provider Id`
ORDER BY total_average DESC LIMIT 0,5)
Union
SELECT
MAX(final_avg_total.`Provider Name`) AS `Hospital Name`,
final_avg_total.`DRG Definition`,
final_avg_total.`Provider Id`,
SUM(final_avg_total.avg_total_payments) AS avg_payments,
SUM(final_avg_total.avg_covered_charges) AS avg_covered,
(SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments)) / SUM(final_avg_total.avg_covered_charges) AS total_average,
1 - (SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments)) / SUM(final_avg_total.avg_covered_charges) AS total_percentage
FROM final_avg_total
GROUP BY final_avg_total.`total_percentage`
ORDER BY total_average DESC LIMIT 0,5
actually both queries are almost same with only Group By is Differing, but i am getting this error.
5 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION (SELECT
MAX(final_avg_total.`Provider Name`) AS `Hospital Name`,
fin'

It can be helpful to opt for a smaller problem, if possible.
See if you get the same results if you
CREATE OR REPLACE VIEW part_one AS ... ;
CREATE OR REPLACE VIEW part_two AS ... ;
and then
SELECT * FROM part_one
UNION
SELECT * FROM part_two;
Letting a database engine comprehend the work on it piece-wise has helped me in times past. Also can aid code maintenance.
If you get dupes, UNION ALL is another handy arrow in the quiver.

this is just a regular UNION with error
http://www.sqlfiddle.com/#!2/ec657/7
and this is the 'same' UNION without error
http://www.sqlfiddle.com/#!2/ec657/8
the only difference is the parenthesis in both case, please be sure to place parenthesis just after the UNION or remove it
...
ORDER BY total_average DESC LIMIT 0,5)
Union
(SELECT --ADDED PARENTHESIS
MAX(final_avg_total.`Provider Name`) AS `Hospital Name`,
...
ORDER BY total_average DESC LIMIT 0,5) --ADDED PARENTHESIS

Related

MySQL row_number in where cause not returning data

I am trying to get the second 10 records from a table with this query but I get no data returned. Take out the where cause and I get data but I have to skip over the first 10 records to get what I am really interested in, trying to avoid that.
SET #row_number = 0;
SELECT
`Ship Date`,`Order Number`,
(#row_number:=#row_number + 1) AS rowid
FROM input_data
WHERE (#row_number>10)
order by #row_number
LIMIT 10;
The WHERE clause cannot reference variables set in the SELECT-list. Despite the order of clauses, the expressions in the SELECT-list have not yet been evaluated as the WHERE clause is filtering rows.
I think you want:
SELECT `Ship Date`, `Order Number` FROM input_data
ORDER BY ...something, I don't know what...
LIMIT 10 OFFSET 10;
Or if you use MySQL 8.0, and can use window functions:
SELECT `Ship Date`, `Order Number`
FROM (
SELECT `Ship Date`, `Order Number`,
ROW_NUMBER() OVER (ORDER BY ...something...) AS rownum
FROM input_data) AS t
WHERE rownum BETWEEN 10 AND 20;
try this, you need to wrap your query into an outer select so rowid is evaluated
SET #row_number = 0;
select * from (
SELECT
`Ship Date`,`Order Number`,
(#row_number:=#row_number + 1) AS rowid
FROM input_date ) A
WHERE A.rowid>1
order by rowid
LIMIT 10;

order by with union in SQL is not working

Is it possible to order when the data comes from many select and union it together? Such as
In this statement, the vouchers data is not showing in the same sequence as I saved on the database, I also tried it with "ORDER BY v_payments.payment_id ASC" but won't be worked
( SELECT order_id as id, order_date as date, ... , time FROM orders WHERE client_code = '$searchId' AND order_status = 1 AND order_date BETWEEN '$start_date' AND '$end_date' ORDER BY time)
UNION
( SELECT vouchers.voucher_id as id, vouchers.payment_date as date, v_payments.account_name as name, ac_balance as oldBalance, v_payments.debit as debitAmount, v_payments.description as descriptions,
vouchers.v_no as v_no, vouchers.v_type as v_type, v_payments.credit as creditAmount, time, zero as tax, zero as freightAmount FROM vouchers INNER JOIN v_payments
ON vouchers.voucher_id = v_payments.voucher_id WHERE v_payments.client_code = '$searchId' AND voucher_status = 1 AND vouchers.payment_date BETWEEN '$start_date' AND '$end_date' ORDER BY v_payments.payment_id ASC , time )
UNION
( SELECT return_id as id, return_date as date, ... , time FROM w_return WHERE client_code = '$searchId' AND w_return_status = 1 AND return_date BETWEEN '$start_date' AND '$end_date' ORDER BY time)
Wrap the sub-select queries in the union within a SELECT
SELECT id, name
FROM
(
SELECT id, name FROM fruits
UNION
SELECT id, name FROM vegetables
)
foods
ORDER BY name
If you want the order to only apply to one of the sub-selects, use parentheses as you are doing.
Note that depending on your DB, the syntax may differ here. And if that's the case, you may get better help by specifying what DB server (MySQL, SQL Server, etc.) you are using and any error messages that result.
You need to put the ORDER BY at the end of the statement i.e. you are ordering the final resultset after union-ing the 3 intermediate resultsets
To use an ORDER BY or LIMIT clause to sort or limit the entire UNION result, parenthesize the individual SELECT statements and place the ORDER BY or LIMIT after the last one. See link below:
ORDER BY and LIMIT in Unions
(SELECT a FROM t1 WHERE a=10 AND B=1)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a LIMIT 10;

RANK query using PARTITION BY fails in mysql

I tried below query to partition by but which fails with below query, the inner query works
select issueid, task_type, assignee, timeoriginalestimate, CREATED,
dense_rank() over ( partition by issueid order by CREATED desc ) as rank
from(
--- Complex query with p.pname, i.issuenum, cg.issueid, it.pname task_type, i.assignee, i.timeoriginalestimate, cg.CREATED, columns which works fine
)
Exception:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( partition by issueid order by CREATED desc ) as rank
from(
SELECT p.pna' at line 3
Update:
SELECT VERSION(); -- 5.6.27
Although your MySQL version do not support Window function, I am letting this is not the issue. Guess you have a higher version and window function is supported.
Now, in your query you have defined the Alias of a column name to "Rank" which is a reserved keyword for your database and you can not use that as column name.
Hope this below hints will help you-
select
issueid,
task_type,
assignee,
timeoriginalestimate,
CREATED,
dense_rank() over ( partition by issueid order by CREATED desc ) as rn -- change the alias name
from(
-- Your subquery
) A -- Also need to give a Alias name to your sub query
Finally, if you have lower version check this LINK for help to get an idea of creating Row_number or Ranking for MySQL older versions.
In addition, this following sample query will really help you finding solution for different type row_number in mysql-
SET #simple_row_number := 0;
SET #id_wise_row_number := 0;
SET #dense_rank_per_id := 0;
SET #prev := 0;
SELECT *,
#simple_row_number := #simple_row_number + 1 AS simple_row_number,
#id_wise_row_number := IF(issueid > #prev, #id_wise_row_number + 1, #id_wise_row_number) AS id_wise_row_number,
#dense_rank_per_id :=IF(issueid > #prev,1, #dense_rank_per_id + 1) AS dense_rank_per_id,
#prev := A.issueid Prev_IssueId
FROM (
SELECT 1 issueid, '20200601' CREATED UNION ALL
SELECT 1 issueid, '20200401' CREATED UNION ALL
SELECT 1 issueid, '20200501' CREATED UNION ALL
SELECT 1 issueid, '20200201' CREATED UNION ALL
SELECT 1 issueid, '20200301' CREATED UNION ALL
SELECT 2 issueid, '20200301' CREATED UNION ALL
SELECT 2 issueid, '20200201' CREATED UNION ALL
SELECT 2 issueid, '20200401' CREATED
) A
ORDER BY issueid, CREATED DESC

Creating table for union query - syntax error

I need to create a table from the union of two queries.
This query works exactly as I need it to:
SELECT portligh_lotteryTest.scores.team FROM portligh_lotteryTest.scores ORDER BY portligh_lotteryTest.scores.count DESC LIMIT 5
union
SELECT portligh_lotteryTest.scores.team FROM portligh_lotteryTest.scores ORDER BY portligh_lotteryTest.scores.count ASC LIMIT 3
Once I add the create statement I begin to get errors
CREATE TABLE portligh_lotteryTest.cTop8 (team int) AS
(SELECT portligh_lotteryTest.scores.team FROM portligh_lotteryTest.scores ORDER BY portligh_lotteryTest.scores.count DESC LIMIT 5)
union
(SELECT portligh_lotteryTest.scores.team FROM portligh_lotteryTest.scores ORDER BY portligh_lotteryTest.scores.count ASC LIMIT 3)
The error is:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT portligh_lotteryTest.scores.team FROM portligh_lotteryTest.scores ORDER ' at line 1
You can try below query:-
CREATE TABLE portligh_lotteryTest.cTop8 (team int) AS
(SELECT portligh_lotteryTest.scores.team FROM portligh_lotteryTest.scores ORDER BY portligh_lotteryTest.scores.count DESC LIMIT 5
union all
SELECT portligh_lotteryTest.scores.team FROM portligh_lotteryTest.scores ORDER BY portligh_lotteryTest.scores.count ASC LIMIT 3)

Select count from multiple tables and group by

Help me!
$sql = SELECT `id`, `email`, `avatar`,`fullname`,
SUM(result) as sum_result,
SUM(total) as sum_total,
COUNT(rank) as `top_1` where `itq_exam_thread_test`.`rank` = 1,
COUNT(rank) as `top_2` where `itq_exam_thread_test`.`rank` = 2,
COUNT(rank) as `top_3` where `itq_exam_thread_test`.`rank` = 3
GROUP BY userid_created
ORDER BY sum_result DESC, sum_rate DESC
LIMIT 0, 100';
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'where itq_exam_thread_test.rank = 1,
WHERE is a clause for the entire query, not a modifier in the SELECT clause. What you want is conditional aggregation. In MySQL, doing the count is quite easy, because it treats boolean expressions as integers in a numeric context. So, you can just use SUM():
SELECT id, email, avatar, fullname, SUM(result) as sum_result,
SUM(total) as sum_total,
SUM(rank = 1) as top_1,
SUM(rank = 2) as top_2,
SUM(rank = 3) as top_3
FROM itq_exam_thread_test
GROUP BY userid_created
ORDER BY sum_result DESC
LIMIT 0, 100;
I removed sum_rate from the ORDER BY, because it is not defined.