The same SQL but have different result - mysql

ps:the description show detail with the href: https://segmentfault.com/q/1010000014649728
I run the follow sql :
select * from
(
select *,(#num2 :=
(if(#GROUP199=`C_ISHOT`,#num2+1,if(#GROUP199:=`C_ISHOT`,1,1)))) row_number
from city_code order by C_ISHOT
) result
where row_number<=10
the first run result show the table total numbers,
but the second run result is my expected。 what's the matter with it,and how can I resolve that?

The variables are not initialized.
select *
from ( select *, (#num2 :=(if(#GROUP199=C_ISHOT,#num2+1,if(#GROUP199:=C_ISHOT,1,1)))) row_number
from city_code, ( SELECT #num2 := 0, #GROUP199 := 0 ) init_vars
order by C_ISHOT ) result
where row_number<=10

Related

How to get results from two sql query results

I"m using SET #runtot:=0 at the top of my SQL code and it gets 2 query results:
The first one is:
MySQL returned an empty result set (i.e. zero rows). (Query took
0.0002 seconds.)
The second is:
Showing rows 0 - 7 (8 total, Query took 0.0058 seconds.)
how can i get the results of the second query only?
here is my SQL code:
SET #runtot:=0;
SELECT
fname,
lname,
guests,
phone
FROM (
(SELECT *, 0 AS rt FROM guests_table WHERE status = 2)
UNION
(SELECT *, (#runtot := #runtot + rsvp.guests) AS rt
FROM
(SELECT *
FROM guests_table
WHERE status != 2
) AS rsvp
WHERE #runtot + rsvp.guests <= 4)
)rsvp
ORDER BY rsvp.id ASC
You can set the parameters in the query:
SELECT fname, lname, guests, phone
FROM ((SELECT *, 0 AS rt FROM guests_table WHERE status = 2)
UNION
(SELECT *, (#runtot := #runtot + rsvp.guests) AS rt
FROM (SELECT *
FROM guests_table
WHERE status != 2
) AS rsvp
WHERE #runtot + rsvp.guests <= 4)
) rsvp CROSS JOIN
(SELECT #runtot := 0) params
ORDER BY rsvp.id ASC;
Note that the use of variables in SELECT queries like this has been deprecated. In MySQL 8+, you should be using window functions.
In addition, the "running sum" is reading the rows in an arbitrary order. There is no guarantee that the result will be in the same order as the results.
If you want further help with the query, ask a new question. Provide sample data, desired results, and a clear explanation of the logic.

Error:View's SELECT contains a variable or parameter

I am using MySQL work bench 8 :
I am not able to create this view as I am getting following error:
View's SELECT contains a variable or parameter
Here is my view:
Create view history as
select ShippedDate, round(previous_operation) as DayEnd, DayStart ,Reorderunits,Quantity,reorderlevel from (
select
y.*
, #prev AS previous_Operation
, #prev := DayStart
from
ExpectedHistory y
, (select #prev:=NULL) vars
order by ShippedDate desc
Note : #prev holds an integer value
If you want the previous operation in MySQL 8+, use lead():
create view history as
select ShippedDate, DayStart,
lead(day_start) over (partition by shippeddate) as as dayend,
Reorderunits, Quantity, reorderlevel,
from ExpectedHistory eh;

unable to create view

I am getting error : View's SELECT contains a variable or parameter with the query below.How do I create view for the same.I really appreciate any help.Thanks in Advance.
CREATE VIEW V AS SELECT #rownum := #rownum + 1 AS rank, name, vote
FROM uservotes, (SELECT #rownum := 0) t ORDER BY vote DESC
declare #rownum int
CREATE VIEW V AS SELECT #rownum := #rownum + 1 AS rank, name, vote
FROM uservotes, (SELECT #rownum := 0) t ORDER BY vote DESC
Try like this
CREATE VIEW V AS
(
SELECT (SELECT 1 + COUNT(*) FROM uservotes where votes < T.votes ) AS NUM, name, votes
FROM uservotes T ORDER BY votes DESC
)
Fiddle Demo
You can define a variable in order to get psuedo row number functionality, because MySQL doesn't have any ranking functions:
Can't Use A Variable in a MySQL View
If you do, you'll get the 1351 error, because you can't use a variable in a view due to design. The bug/feature behavior is documented here.

Calculate medians for multiple columns in the same table in one query call

StackOverflow to the rescue!, I need to find the medians for five columns at once, in one query call.
The median calculations below work for single columns, but when combined, multiple uses of "rownum" throws the query off. How can I update this to work for multiple columns? THANK YOU. It's to create a web tool where nonprofits can compare their financial metrics to user-defined peer groups.
SELECT t1_wages.totalwages_pctoftotexp AS median_totalwages_pctoftotexp
FROM (
SELECT #rownum := #rownum +1 AS `row_number` , d_wages.totalwages_pctoftotexp
FROM data_990_c3 d_wages, (
SELECT #rownum :=0
)r_wages
WHERE totalwages_pctoftotexp >0
ORDER BY d_wages.totalwages_pctoftotexp
) AS t1_wages, (
SELECT COUNT( * ) AS total_rows
FROM data_990_c3 d_wages
WHERE totalwages_pctoftotexp >0
) AS t2_wages
WHERE 1
AND t1_wages.row_number = FLOOR( total_rows /2 ) +1
--- [that was one median, below is another] ---
SELECT t1_solvent.solvent_days AS median_solvent_days
FROM (
SELECT #rownum := #rownum +1 AS `row_number` , d_solvent.solvent_days
FROM data_990_c3 d_solvent, (
SELECT #rownum :=0
)r_solvent
WHERE solvent_days >0
ORDER BY d_solvent.solvent_days
) AS t1_solvent, (
SELECT COUNT( * ) AS total_rows
FROM data_990_c3 d_solvent
WHERE solvent_days >0
) AS t2_solvent
WHERE 1
AND t1_solvent.row_number = FLOOR( total_rows /2 ) +1
[those are two - there are five in total I'll eventually need to find medians for at once]
This kind of thing is a big pain in the neck in MySQL. You might be wise to use the free Oracle Express Edition or postgreSQL if you're going to do tonnage of this statistical ranking work. They all have MEDIAN(value) aggregate functions that are either built-in or available as extensions. Here's a little sqlfiddle demonstrating that. http://sqlfiddle.com/#!4/53de8/6/0
But you didn't ask about that.
In MySQL, your basic problem is the scope of variables like #rownum. You also have a pivoting problem: that is, you need to turn rows of your query into columns.
Let's tackle the pivot problem first. What you're going to do is create a union of several big fat queries. For example:
SELECT 'median_wages' AS tag, wages AS value
FROM (big fat query making median wages) A
UNION
SELECT 'median_volunteer_hours' AS tag, hours AS value
FROM (big fat query making median volunteer hours) B
UNION
SELECT 'median_solvent_days' AS tag, days AS value
FROM (big fat query making median solvency days) C
So here are your results in a table of tag / value pairs. You can pivot that table like so, to get one row with a value in each column.
SELECT SUM( CASE tag WHEN 'median_wages' THEN value ELSE 0 END
) AS median_wages,
SELECT SUM( CASE tag WHEN 'median_volunteer_hours' THEN value ELSE 0 END
) AS median_volunteer_hours,
SELECT SUM( CASE tag WHEN 'median_solvent_days' THEN value ELSE 0 END
) AS median_solvent_days
FROM (
/* the above gigantic UNION query */
) Q
That's how you pivot up rows (from the UNION query in this case) to columns. Here's a tutorial on the topic. http://www.artfulsoftware.com/infotree/qrytip.php?id=523
Now we need to tackle the median-computing subqueries. The code in your question looks pretty good. I don't have your data so it's hard for me to evaluate it.
But you need to avoid reusing the #rownum variable. Call it #rownum1 in one of your queries, #rownum2 in the next one, and so on. Here's a dinky sql fiddle doing just one of these. http://sqlfiddle.com/#!2/2f770/1/0
Now let's build it up a bit, doing two different medians. Here's the fiddle http://sqlfiddle.com/#!2/2f770/2/0 and here's the UNION query. Notice the second half of the union query uses #rownum2 instead of #rownum.
Finally, here's the full query with the pivoting. http://sqlfiddle.com/#!2/2f770/13/0
SELECT SUM( CASE tag WHEN 'Boston' THEN value ELSE 0 END ) AS Boston,
SUM( CASE tag WHEN 'Bronx' THEN value ELSE 0 END ) AS Bronx
FROM (
SELECT 'Boston' AS tag, pop AS VALUE
FROM (
SELECT #rownum := #rownum +1 AS `row_number` , pop
FROM pops,
(SELECT #rownum :=0)r
WHERE pop >0 AND city = 'Boston'
ORDER BY pop
) AS ordered_rows,
(
SELECT COUNT( * ) AS total_rows
FROM pops
WHERE pop >0 AND city = 'Boston'
) AS rowcount
WHERE ordered_rows.row_number = FLOOR( total_rows /2 ) +1
UNION ALL
SELECT 'Bronx' AS tag, pop AS VALUE
FROM (
SELECT #rownum2 := #rownum2 +1 AS `row_number` , pop
FROM pops,
(SELECT #rownum2 :=0)r
WHERE pop >0 AND city = 'Bronx'
ORDER BY pop
) AS ordered_rows,
(
SELECT COUNT( * ) AS total_rows
FROM pops
WHERE pop >0 AND city = 'Bronx'
) AS rowcount
WHERE ordered_rows.row_number = FLOOR( total_rows /2 ) +1
) D
This is just two medians. You need five. I think it's easy to make the case that this median computation is absurdly difficult to do in MySQL in a single query.
Suppose you have a table with three columns like table(key, value1, value2).
this query gives you the median value of the two value columns for each key:
SELECT key,
((array_agg(value1 order by value1 asc) )[floor( (count(*)+1)::float/2)] + (array_agg(value1 order by value1 asc) )[ceiling( (count(*)+1)::float/2) ] )/2,
((array_agg(value2 order by value2 asc) )[floor( (count(*)+1)::float/2)] + (array_agg(value2 order by value2 asc) )[ceiling( (count(*)+1)::float/2) ] )/2
FROM table
GROUP BY key

Getting latest rows in MySQL based on date (grouped by another column)

This type of question is asked every now and then. The queries provided works, but it affects performance.
I have tried the JOIN method:
SELECT *
FROM nbk_tabl
INNER JOIN (
SELECT ITEM_NO, MAX(REF_DATE) as LDATE
FROM nbk_tabl
GROUP BY ITEM_NO) nbk2
ON nbk_tabl.REF_DATE = nbk2.LDATE
AND nbk_tabl.ITEM_NO = nbk2.ITEM_NO
And the tuple one (way slower):
SELECT *
FROM nbk_tabl
WHERE REF_DATE IN (
SELECT MAX(REF_DATE)
FROM nbk_tabl
GROUP BY ITEM_NO
)
Is there any other performance friendly way of doing this?
EDIT: To be clear, I'm applying this to a table with thousands of rows.
Yes, there is a faster way.
select *
from nbk_table
order by ref_date desc
limit <n>
Where is the number of rows that you want to return.
Hold on. I see you are trying to do this for a particular item. You might try this:
select *
from nbk_table n
where ref_date = (select max(ref_date) from nbk_table n2 where n.item_no = n2.item_no)
It might optimize better than the "in" version.
Also in MySQL you can use user variables (Suppose nbk_tabl.Item_no<>0):
select *
from (
select nbk_tabl.*,
#i := if(#ITEM_NO = ITEM_NO, #i + 1, 1) as row_num,
#ITEM_NO := ITEM_NO as t_itemNo
from nbk_tabl,(select #i := 0, #ITEM_NO := 0) t
order by Item_no, REF_DATE DESC
) as x where x.row_num = 1;