Prepending a row in the result of a MySQL query? - mysql

Reading this answer to a SO question on how to append a row onto a MySQL result, we can do the following to append the value Jason to the names of Customers:
Select NAME
From Customers
UNION ALL
Select 'Jason'
So we end up with:
NAME
Actual Customer 1
Actual Customer 2
Jason
But how could we add Jason to the beginning of the results so what we have:
NAME
Jason
Actual Customer 1
Actual Customer 2
(Would like to do this without using Order By)

Have you tried this
Select 'Jason' As `Name`
UNION ALL
Select Name
From Customers
If you want the second query ordered then use something like
Select 'Jason' As `Name`
UNION ALL
(Select `myDate`
From Customers
Order By `myDate`
)

Related

Operating on a table received from query within the same query SQL

So I have this table resulting from a query. Is there a way to combine all of the purchases for the same username and order them in desc order to find the most loyal customers within the same query? maybe saving it to a variable and then doing something?
username
number_of_purchase
Bob
1
Marry
3
Mike
2
Bob
2
Marry
3
Mike
4
Ariana
3
Sally
1
This should do the work!
You can read about CTE here - https://learn.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-ver15.
with users as (
**YOUR QUERY HERE **
)
Select username, sum(number_of_purchase) from users
group by username
Example from Microsoft site:
-- Define the CTE expression name and column list.
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
AS
-- Define the CTE query.
(
SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
FROM Sales.SalesOrderHeader
WHERE SalesPersonID IS NOT NULL
)
-- Define the outer query referencing the CTE name.
SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
FROM Sales_CTE
GROUP BY SalesYear, SalesPersonID
ORDER BY SalesPersonID, SalesYear;
Depending on your MySql version. If prior to v8 then you can use a derived table, basically, wrapping your existing query as follows
Select username, sum(number_of_purchase) purchases
from (
> Existing query <
)t
group by username
order by purchases desc
If you are using MySql 8 you could use window functions in your existing query to materialize the sum of purchases per user which you can then order by.
Without your existing query all I can do us suggest you incorporate the following, using the applicable column names
sum(purchase count column) over(partition by username) TotalPurchases

How do I get the top 4 results of a column in mysql query?

I'm not very experienced in mySQL, but
I have a SQL query table where I need to return:
Salary_amount_1
Salary_amount_2
Salary_amount_3
Salary_amount_4
(not relevant below)
Salary_Date_1
Salary_Date_2
Salary_Date_3
Salary_Date_4
I've got 4 seperate columns for each salary amount to select into in the destination table we're inserting into, and a column called Salary with 15+ different amounts in the source table we're selecting from, but how do I specifically select the first salary for column 1, second for column two, third for three and fourth salary for column four?
Thanks in advance
What I have tried:
This is what I have (and isn't working for me yet)
Select
ID,
Bank Name,
UserName,
min(details_Credit) as Salary_Amount_1,
max(details_Credit) as Salary_Amount_2,
Case
when details_Credit = min(details_Credit)
and details_Credit > min(details_Credit)
end Salary_Amount_3,
????? as Salary_Amount_4,
any help would be appreciated. thank you
Sample Data:
Salary| SalaryDate| UserName| BankName
=====================================
1000 |2013-05-23 |MikeRoss |NetBank
1500 |2013-06-23 |MikeRoss |NetBank
2000 |2013-07-22 |MikeRoss |NetBank
1000 |2013-08-15 |MikeRoss |NetBank
Desired Results:
Username|Bank|Salary1|Salary2|Salary3|Salary4|Date1|Date2|Date3|Date4
MikeRoss|Netbank|1000|1500|2000|1000|2013-05-23| 2013-06-23| 2013-06-22| 2013-08-15
I think what you need is something like this:
Select ID, Bank Name, UserName, Salary_amount_1 from yourTable
order by Salary_amount_1 limit 1
Union
Select ID, Bank Name, UserName, Salary_amount_2 from yourTable
order by Salary_amount_2 limit 1,1
Union
Select ID, Bank Name, UserName, Salary_amount_3 from yourTable
order by Salary_amount_3 limit 2,1
Union
Select ID, Bank Name, UserName, Salary_amount_4 from yourTable
order by Salary_amount_4 limit 3,1
This will perform 4 queries, each returning one of your desired results.
limit offset, rowcount will take the first rowcount rows after skipping offset rows.
That said, I strongly advice you to check the structure of your table.
I used Left Join instead to resolve this incase anyone is wondering. i.e
left join DB.Table_Name as a1 on a1.ID=a.ID and a1.TransactionDate=a0.maxDate
left join DB.Table_Name as a2 on a2.ID=a1.ID and a2.TransactionDate<a1.TransactionDate
left join DB.Table_Name as a3 on a3.ID=a2.ID and a3.TransactionDate<a2.TransactionDate
etc

how to fetch the data which has only single entry in a column in the table in mysql?

I have a table named as scholar and it has a column studentid now i
want to fetch the data where studentid comes only once, one id can have multiple entry in the studentid column
below is my structure data
now i want to get studentid = 123 and 154 all data as these came only once
like below is my desired output:
so what will be the query for that please help
I think you want a query like this:
SELECT *,count(*) as cnt FROM scholar GROUP BY studentid HAVING cnt = 1
But not this is the fastest solution.
Or you can use this:
SELECT * FROM scholar GROUP BY studentid HAVING count(id) = 1

Complex Query using Multiple Columns in a single table

Let's say that I have a table of race results. The table consists of seven columns as follows: Date ( MySql Date format of xxxx-xx-xx ), and one column each for the names of the top six finishers named First, Second, Third, Fourth, Fifth, and Sixth. I have a several sets of results and maybe 100 or so different names in the various finisher columns. I need a query that would allow me to list each person whose name has appeared in any of the finisher columns ( First, Second, Third, Fourth, Fifth, Sixth ) along with only the most recent date that their name appeared. I do NOT need separate results based on finish place, so I need all six of the finisher columns lumped together. Most of the names will appear on dozens of different dates, but I only need the most recent date that each name appeared. Ideally the result would generate a list of each name and their most recent finish date, sorted from least recent to most recent. I tried to create a fiddle to demonstrate this but for whatever reason I could not get the date to work correctly in the fiddle. Anyway, anyone who can offer even a shred of help on this would be greatly appreciated.
SELECT <table>.date, <table>.first as name FROM <table> GROUP BY name
UNION DISTINCT
SELECT <table>.date, <table>.second as name FROM <table> GROUP BY name
UNION DISTINCT
SELECT <table>.date, <table>.third as name FROM <table> GROUP BY name
UNION DISTINCT
SELECT <table>.date, <table>.fourth as name FROM <table> GROUP BY name
UNION DISTINCT
SELECT <table>.date, <table>.fifth as name FROM <table> GROUP BY name
UNION DISTINCT
SELECT <table>.date, <table>.sixth as name FROM <table> GROUP BY name
ORDER BY date
This gave me exactly the results I needed. I basically just used "name" to catch the finishers, and "MAX(Date) as last" to pick out only the most recent showing for each "name" when I queried all six columns.
SELECT name, MAX(Date) as last
FROM (
SELECT first name,Date FROM Results
UNION ALL
SELECT second, Date FROM Results
UNION ALL
SELECT third, Date FROM Results
UNION ALL
SELECT fourth, Date FROM Results
UNION ALL
SELECT fifth, Date FROM Results
UNION ALL
SELECT sixth, Date FROM Results) Q
GROUP BY name
ORDER BY last ASC;
select t.first, a.date from (select distinct(first) from race union select distinct(second) from race union select distinct(third) from race union select distinct(fourth) from race union select distinct(fifth) from race union select distinct(sixth) from race) as t, race a where t.first in (a.first, a.second, a.third, a.fourth, a.fifth, a.sixth)

Select distinct column along with some other columns in MySQL

I can't seem to find a suitable solution for the following (probably an age old) problem so hoping someone can shed some light. I need to return 1 distinct column along with other non distinct columns in mySQL.
I have the following table in mySQL:
id name destination rating country
----------------------------------------------------
1 James Barbados 5 WI
2 Andrew Antigua 6 WI
3 James Barbados 3 WI
4 Declan Trinidad 2 WI
5 Steve Barbados 4 WI
6 Declan Trinidad 3 WI
I would like SQL statement to return the DISTINCT name along with the destination, rating based on country.
id name destination rating country
----------------------------------------------------
1 James Barbados 5 WI
2 Andrew Antigua 6 WI
4 Declan Trinidad 2 WI
5 Steve Barbados 4 WI
As you can see, James and Declan have different ratings, but the same name, so they are returned only once.
The following query returns all rows because the ratings are different. Is there anyway I can return the above result set?
SELECT (distinct name), destination, rating
FROM table
WHERE country = 'WI'
ORDER BY id
Using a subquery, you can get the highest id for each name, then select the rest of the rows based on that:
SELECT * FROM table
WHERE id IN (
SELECT MAX(id) FROM table GROUP BY name
)
If you'd prefer, use MIN(id) to get the first record for each name instead of the last.
It can also be done with an INNER JOIN against the subquery. For this purpose the performance should be similar, and sometimes you need to join on two columns from the subquery.
SELECT
table.*
FROM
table
INNER JOIN (
SELECT MAX(id) AS id FROM table GROUP BY name
) maxid ON table.id = maxid.id
The problem is that distinct works across the entire return set and not just the first field. Otherwise MySQL wouldn't know what record to return. So, you want to have some sort of group function on rating, whether MAX, MIN, GROUP_CONCAT, AVG, or several other functions.
Michael has already posted a good answer, so I'm not going to re-write the query.
I agree with #rcdmk . Using a DEPENDENT subquery can kill performance, GROUP BY seems more suitable provided that you have already INDEXed the country field and only a few rows will reach the server. Rewriting the query giben by #rcdmk , I added the ORDER BY NULL clause to suppress the implicit ordering by GROUP BY, to make it a little faster:
SELECT MIN(id) as id, name, destination as rating, country
FROM table WHERE country = 'WI'
GROUP BY name, destination ORDER BY NULL
You can do a GROUP BY clause:
SELECT MIN(id) AS id, name, destination, AVG(rating) AS rating, country
FROM TABLE_NAME
GROUP BY name, destination, country
This query would perform better in large datasets than the subquery alternatives and it can be easier to read as well.