Combining select distinct and order by - mysql

This is my SQL query :
SELECT DISTINCT dest
FROM messages
WHERE exp = ?
UNION
SELECT DISTINCT exp
FROM messages
WHERE dest = ?
With this query, I get all the messages I've sent or received. But in my table messages, i have a field timestamp, and i need, with this query, add an order by timestamp... but how ?

You can do this without a union:
SELECT (case when exp = ? then dest else exp end), timestamp
FROM messages
WHERE exp = ? or dest = ?;
Then to get the most recent message for each participant, use group by not distinct:
SELECT (case when exp = ? then dest else exp end) as other, max(timestamp)
FROM messages
WHERE exp = ? or dest = ?
group by (case when exp = ? then dest else exp end)
order by max(timestamp) desc;

SELECT *
FROM
( SELECT
col1 = dest,
col2 = MAX(timestampCol)
FROM
messages
WHERE
exp = ?
GROUP BY
dest
UNION
SELECT
col1 = exp,
col2 = MAX(timestampCol)
FROM
messages
WHERE
dest= ?
GROUP BY
exp
) tbl
ORDER BY col2
This should return only one row per distinct exp / dest though I'm sure this could probably be done without a union; The GROUP BY will only get the most recent one.
Updated SQL: Given that it is possible for an exp on one record to equal a dest on the same or another record.
SELECT
CASE WHEN exp = ? THEN dest ELSE exp END AS col1
,MAX(timestampCol) AS col2
FROM
messages
WHERE
exp = ?
OR dest = ?
GROUP BY
(CASE WHEN exp = ? THEN dest ELSE exp END)
ORDER BY
MAX(timestampCol) DESC;
You might want to consider adding an SQL Fiddle with some dummy data to allow users to better help you.

SELECT *
FROM
(
SELECT DISTINCT dest AS Column1, timestamp AS Column2
FROM messages
WHERE exp = ?
UNION
SELECT DISTINCT exp AS Column1, timestamp AS Column2
FROM messages
WHERE dest = ?
) tbl
ORDER BY Column2

This query will help you in getting records order by timestamp
SELECT tbl.mailId, Max(timestampColumn) MostRecentDate
FROM
(
SELECT exp AS mailId, Max(timestampCol) AS timestampColumn
FROM Employeeatd
WHERE dest = ?
GROUP BY exp
UNION
SELECT Dept AS abc, Max(timestampCol) AS timestampColumn
FROM Employeeatd
WHERE exp = ?
GROUP BY Dept
) tbl
GROUP BY mailId
ORDER BY Max(timestampColumn) desc

Related

MS SQL query with multiple search criteria across rows

I have below table and SQL query written, this query should not return any result but its returning ID = 1 , what is wrong with the SQL query? Can anyone please help?
** Note balance data type is decimal rest are varchar
ID code balance level
1 C 150.00
1 P 40027.42 F
1 P 40027.42 F
select distinct ID from table
(
(code = 'P' and balance = 40027.42 and level = 'F') or
(code = 'C' and balance = 151.00 )
)
group by ID
having count(ID) >=2
If you do not want to count the same code twice, you can use count(distinct code):
select ID
from t
where (code = 'P' and balance = 40027.42 and level = 'F')
or (code = 'C' and balance = 151.00 )
group by ID
having count(distinct code) >=2
If you want to only count a distinct set of values once, you can use a derived table/subquery to select distinct rows:
select ID
from (
select distinct id, code, balance, level
from t
) as s
where (code = 'P' and balance = 40027.42 and level = 'F')
or (code = 'C' and balance = 151.00 )
group by ID
having count(ID) >=2
rextester demo for both: http://rextester.com/LBKO57534

Sum of two counts from different table with different conditions

Basically I need to merge these into one single query:
SELECT COUNT( DISTINCT id ) AS totalRows1
FROM other_events WHERE status = "approved"
AND Location = 1
SELECT COUNT( DISTINCT Id ) AS totalRows2
FROM core_events WHERE Status = "Active"
AND Location_id = 1
When I do it like below, if there is no event with Location_id = 1 query returns 0. In that condition I need it to return the count of the first table only.
SELECT COUNT( DISTINCT t1.id ) + COUNT( DISTINCT t2.Id ) AS total
FROM other_events AS t1, core_events AS t2
WHERE t1.status = "approved"
AND t1.Location = 1
AND t2.Location_id = 1
AND t2.Status = 'Active'
ps. column names are exactly like above
Use a UNION statement to merge the result like this:
SELECT SUM(total) FROM (
SELECT COUNT(DISTINCT id) AS total
FROM other_events
WHERE (status = "approved" AND Location = 1)
UNION ALL
SELECT COUNT(DISTINCT Id) AS total
FROM core_events
WHERE (Location_id = 1 AND Status = 'Active')
) union_result

DB2 Show the latest row record from users, using the date and time

I have 100 records from 3 users. I want to show the most recent record from each user. I have the following query:
SELECT *
FROM Mytable
WHERE Dateabc = CURRENT DATE
AND timeabc =
(
SELECT MAX(timeabc)
FROM Mytable
)
It returns the most recent record for everyone, and I need it to return most recent record from every user.
Should the solution support both DB2 and mysql?
SELECT * FROM Mytable as x
WHERE Dateabc = CURRENT_DATE
AND timeabc = (SELECT MAX( timeabc ) FROM Mytable as y where x.user = y.user)
If it's only DB2 more efficient solutions exists:
SELECT * from (
SELECT x.*, row_number() over (partition by user order by timeabc desc) as rn
FROM Mytable as x
)
WHERE rn = 1
I assume somewhere in your table you have a userID...
select userID, max(timeabc) from mytable group by userID
SELECT *
FROM Mytable as a
WHERE Dateabc = CURRENT_DATE
AND timeabc =
(
SELECT MAX( timeabc )
FROM Mytable as b
WHERE a.uId = b.uId
)

Compute multiple queries in mysql

I have 3 queries, the first one is like this
SELECT amount FROM table1
WHERE id = "1"
the output of this is
amount
10000
then my second query
SELECT SUM(hours * 10) as hours FROM table2
WHERE empid = "1"
output is
hours
400
and then my third query
SELECT totalcost FROM table3
WHERE id = "1"
output
totalcost
5000
I added the value of the second and third query
SELECT 'SUMQ2Q3',
(SELECT SUM(hours * 10) as hours FROM table2
WHERE empid = "1")
+
(SELECT totalcost FROM table3
WHERE id = "1")
and got the output of
5400
Next thing that I want to happen is to minus the value of the first query to the output i got when i sum the second and third query.
But i keep on getting a syntax error. It currently looks like this
SELECT amount FROM table1
WHERE id = "1"
-
SELECT
(SELECT SUM(hours * 10) as hours FROM table2
WHERE empid = "1"
+
SELECT totalcost FROM table3
WHERE id = "1")
How is the right way to do this?
Unfortunately no DB here, but
SELECT t1.amount - t2.sum + t3.totalcost
FROM (SELECT amount FROM table1 WHERE id = "1") as t1,
(SELECT SUM(hours * 10) as hours FROM table2 WHERE empid = "1") as t2
(SELECT totalcost FROM table3 WHERE id = "1") as t3
might do the job.
How about trying
SELECT
(SELECT amount FROM table1 WHERE id = "1")
- (SELECT SUM(hours * 10) as hours FROM table2 WHERE empid = "1")
- (SELECT totalcost FROM table3 WHERE id = "1")
SELECT (
(
SELECT amount FROM table1 WHERE id = "1") As x -
(SELECT SUM(hours * 10) as hours FROM table2 WHERE empid = "1") As y +
(SELECT totalcost FROM table3 WHERE id = "1") As z
)
As answer

fetch no of rows from table 2 with id of table 1

I have some thing to do here with subquery but I am not able to do.
I want the result from a table with a extra field to show to no of results from other table with a column value from table 1.
table1:
CountryId Country ISO2 ISO3
table2:
id noof_country state
I have to retrive noof_country count in table 1 as count field
EDIT
my actual tables are
table 1:
ad_id job_country status delete days_left
table 2:
CountryId Country ISO2 status
I have done query in two phase:
$sql_map = "select distinct c.ISO2, c.Country, a.job_country
from rec_countries c, rec_advert a
where c.status = 1
and DATE(a.modified_date) >= CURDATE() - INTERVAL 30 DAY
and c.ISO2 <> '--'
and c.ISO2 <> ''
and c.CountryId = a.job_country
and a.status = 1
and a.`delete` = 0
and a.days_left >0
";
$res = mysql_query($sql_map);
while($row = mysql_fetch_array($res)){
$jobs_no = count($row['job_country']);
$sql_job = "SELECT COUNT( job_country ) AS jobs_no
FROM rec_advert
WHERE job_country = ".$row['job_country']."
and status = 1
and `delete` = 0
and days_left >0";
$resjob=mysql_query($sql_job);
$rowjob = mysql_fetch_array($resjob);
//here jobs_no is the count of total rows
}
Here I want to do with subquery.
If I read the question right, this should work:
SELECT
CountryId,
Country,
ISO2,
ISO3,
(
SELECT COUNT(DISTINCT noof_country)
FROM table2
WHERE table2.id = table1.CountryId
) AS noof_country_count
FROM table1
It's not immediately clear in your question which column in table1 is a foreign key to which column in table2... or if they are even related that way. If this query doesn't work for you, please clarify your schema.
Based on your updated information, try this:
select distinct c.ISO2, c.Country, a.job_country,
(
select COUNT(a2.job_country)
from rec_advert a2
where a2.job_country = a.job_country
and a2.status = 1
and a2.`delete` = 0
and a2.days_left >0
) as jobs_no
from rec_countries c, rec_advert a
where c.status = 1
and DATE(a.modified_date) >= CURDATE() - INTERVAL 30 DAY
and c.ISO2 <> '--'
and c.ISO2 <> ''
and c.CountryId = a.job_country
and a.status = 1
and a.`delete` = 0
and a.days_left >0