MS SQL query with multiple search criteria across rows - sql-server-2008

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

Related

mysql GROUP CONCAT not returning values

Here is my query
SELECT
SUM(o.order_disc + o.order_disc_vat) AS manualsale
FROM
orders o
WHERE
o.order_flag IN (0 , 2, 3)
AND o.order_status = '1'
AND (o.assign_sale_id IN (SELECT GROUP_CONCAT(CAST(id AS SIGNED)) AS ids FROM users WHERE team_id = 92))
AND DATE(o.payment_on) = DATE(NOW())
above query return null when i run this query in terminal
When i use subquery below it returns data
SELECT GROUP_CONCAT(CAST(id AS SIGNED)) AS ids FROM users WHERE team_id = 92)
above query returns
'106,124,142,179'
and when i run my first query like below
SELECT
SUM(o.order_disc + o.order_disc_vat) AS manualsale
FROM
orders o
WHERE
o.order_flag IN (0 , 2, 3)
AND o.order_status = '1'
AND (o.assign_sale_id IN (106,124,142,179))
AND DATE(o.payment_on) = DATE(NOW())
it return me value.
Why it is not working with subquery please help
This does not do what you want:
AND (o.assign_sale_id IN (SELECT GROUP_CONCAT(CAST(id AS SIGNED)) AS ids FROM users WHERE team_id = 92))
This compares a single value against a comma-separated list of values, so it never matches (unless there is just one row in users for the given team).
You could phrase this as:
AND assign_sale_id IN (SELECT id FROM users WHERE team_id = 92)
But this would probably be more efficently expressed with exists:
AND EXISTS(SELECT 1 FROM users u WHERE u.team_id = 92 AND u.id = o.assign_sale_id)
Side note: I would also recommend rewriting this condition:
AND DATE(o.payment_on) = DATE(NOW())
To the following, which can take advantage of an index:
AND o.payment_on >= current_date AND o.payment_on < current_date + interval 1 day

How to select last and last but one records

I have a table with 3 columns id, type, value like in image below.
What I'm trying to do is to make a query to get the data in this format:
type previous current
month-1 666 999
month-2 200 15
month-3 0 12
I made this query but it gets just the last value
select *
from statistics
where id in (select max(id) from statistics group by type)
order
by type
EDIT: Live example http://sqlfiddle.com/#!9/af81da/1
Thanks!
I would write this as:
select s.*,
(select s2.value
from statistics s2
where s2.type = s.type
order by id desc
limit 1, 1
) value_prev
from statistics s
where id in (select max(id) from statistics s group by type) order by type;
This should be relatively efficient with an index on statistics(type, id).
select
type,
ifnull(max(case when seq = 2 then value end),0 ) previous,
max( case when seq = 1 then value end ) current
from
(
select *, (select count(*)
from statistics s
where s.type = statistics.type
and s.id >= statistics.id) seq
from statistics ) t
where seq <= 2
group by type

How to calculate Sum of 2 Count(*) in Mysql

I have two tables that I count rows of them.
SELECT COUNT(*)
FROM docgrados_directores
WHERE docgrados_directoresleido = '0' AND docgrados_directoresusu = '11'
result 1
SELECT COUNT(*)
FROM docgrados_lectores
WHERE docgrados_lectoresleido = '0' AND docgrados_lectoresusu = '11'
result 1
I need total count (result would be 2). How can I sum the result with a single statement? What is the correct syntax??
Use another SELECT to add the scalar values returned by your queries:
SELECT (SELECT COUNT(*)
FROM docgrados_directores
WHERE docgrados_directoresleido = '0' AND docgrados_directoresusu = '11' )
+
(SELECT COUNT(*)
FROM docgrados_lectores
WHERE docgrados_lectoresleido = '0' AND docgrados_lectoresusu = '11')
The above statement should return 2 as result if the result of both subqueries is a 1.

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

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