How can i do it in single SQL? - sql

I have this Table like this
ID | NAME | AGE | ADDRESS | SALARY
and an ID (2)
AGE of ID 2 is 25,
Now i need to count total number of record with AGE 25. How can i do it in single SQL Query? is there any why?
i currently doing it in 2 query. in one i return AGE with ID.
select AGE from table_name where ID = 2
it return AGE 25
and 2nd query i count number of record with this AGE.
select COUNT(*) from table_name where age =25
i want to do it in one SQL Query. is there any way ?

use SQL COUNT function
select COUNT(*) from mytable where age =25

You want to count the number of rows with the same age as the specified ID?
You can use a windowed count
select Agecount
from (
select *, Count(*) over (partition by Age) Agecount
from YourTable
)t
where id=?

Use Group by with subquery
SELECT COUNT(*) AS ageCount
FROM table_name
WHERE age in (SELECT age FROM table_name WHERE ID = 2)
GROUP BY age

For Questions like this the best way is use multiple conditions using Where keyword with And-Or Operators.
This query should work for your requirement without complicating anything.
select count(*) from table_name where ID=2 and age=25;

Related

join and group by in SQL

I have two tables that I was going to join, but I understand it's more efficient to use CREATE VIEW. This is what I have:
CREATE OR REPLACE VIEW view0_joinedTablesGrouped
AS
Select table1.*,table2.*
FROM table1
inner join table2 on table1.col =
table2.matchingcol
group by table2.matchingcol;
which causes the following error:
ERROR: column "table1.col" must appear in the GROUP BY clause or be
used in an aggregate function
LINE 3: Select table.*,table2.*
Group By cannot do what you are trying to do.
Consider a simple table:
Name Age
-------
Ann 10
Bill 10
Chris 11
If you try to group by age with:
Select * from Table group by Age
What, exactly, do you expect to appear in the Name column for Age=10? Ann, or Bill or both or neither or ....? There is no good answer.
So, when you group by, every column in the output has to be an aggregate – that means a function of every row in the group.
So these are valid:
Select Age, Count(*) from Table group by Age
Select Age, Max( Length(Name)) from Table group by Age
Select Age, Max(Name) from Table group by Age
But this is impossible to do, and isn't valid:
Select Age,Name from Table group by Age
So your select * is the problem -- you can't just select column values because when you group by there's a whole group of column values for every output row, and you can't stuff all those values into one column of one row.
As for using a view, #systemjack's comment is correct.

SQL query to select most recent of duplicates

I have a table of values, with a date stored against each entry for example
Name
Age
PaymentAmount
Date
Can someone help me to write a query that would show the most recent payment only of any person within a certain age range.
E.g If I had 5 entries, and wanted the most recent payment of all people aged 20-25
Allan, 45, $1500, 1/1/2014
Tim, 22, $1500, 1/2/2001
John, 25, $2000, 2/3/2001
Tim, 22, $2500, 1/2/2010
John, 25, $3000, 2/3/2010
It would return the bottom 2 rows only
You didn't state your DBMS, so this is ANSI SQL
select *
from (
select name,
age,
PaymentAmount,
Date,
row_number() over (partition by name order by date desc) as rn
from the_table
where age between 22 and 25
) t
where rn = 1;
Another option is to use a co-related subquery:
select name,age,paymentamount,date
from the_table t1
where age between 22 and 25
and date = (select max(date)
from the_table t2
where t2.name = t1.name
and t2.age between 22 and 25)
order by name;
Usually the solution with a window function is faster than the co-related subquery as only a single access to the table is needed.
SQLFiddle: http://sqlfiddle.com/#!15/17e37/4
Btw: having a column named age is a bit suspicious because you need to update that every year. You should rather store the date of birth and then calculate the age when retrieving the data.
This query would give you all records of most recent payment of age 20 and 25. Limit it by using TOP 2 or LIMIT 2 or rownum <=2 as per your DB syntax
SELECT NAME,AGE,PAYMENTAMOUNT,DATE FROM MY_TABLE
WHERE AGE BETWEEN 20 AND 25
AND DATE IN
(
SELECT MAX(DATE)
FROM MY_TABLE
WHERE
AGE BETWEEN 20 AND 25
);
EDIT as per horse_with_no_name:
SELECT NAME,AGE,PAYMENTAMOUNT,DATE
FROM the_table
WHERE AGE BETWEEN 20 AND 25
AND DATE IN
(
SELECT (DATE)
FROM the_table
WHERE
AGE BETWEEN 20 AND 25 order by date desc limit 2
)
limit 2;
Fiddle reference : http://sqlfiddle.com/#!15/17e37/10
Simplest of all,Try this following query
select name,age,paymentamount,date from yourtablename where date in (select max(date) from yourtablename where age between 20 and 25 and group by name);
You should Create a Table with Identity Column to make your Life easier
ColumnPrimaryKey IDENTITY (1,1)
Name
Age
PaymentAmount
Date
SELECT TOP 2 * FROM [TableName] Where Age BETWEEN 20 AND 25 ORDER BY [PrimaryKey] DESC
The above query will return the top two row Inserted in table
You can use between like
select * from meta where title='$title' and (date between '$start_date' and '$end_date').
Okay, I know you said SQL-- here's for people with two layers.
VIA SQL:
Order your SQL results by date descending (should be newest to oldest...).
VIA YOUR "BACK END":
Create an empty final set.
As you are iterating through your results, if your result row person is not in your final set, add the data to the final set.
Boom, your final set has the latest of each person.

Get first row in Oracle Sql

I am trying to get only the first row from this query. The query does not return the top row. Here is the query.
SELECT DISTINCT name, age
FROM donates, persons
WHERE name = donor
AND name IN (SELECT receiver FROM donates)
AND ROWNUM <= 1
ORDER BY age DESC;
When I run the query it returns Chirs |35.
Without the ROWNUM <=1 this is what the table looks like.
NAME | AGE
-------------
george | 62
Chris | 35
zara | 24
I think the best way to get this is to use a subquery as the rownum is being looked at before the order by so:
select * from (
SELECT DISTINCT name, age
FROM donates, persons
WHERE name = donor
AND name IN (SELECT receiver FROM donates)
ORDER BY age DESC
) where ROWNUM <= 1;
For a longer read look at http://www.oracle.com/technetwork/issue-archive/2006/06-sep/o56asktom-086197.html
Try to use ROWID rather than ROWNUM like this:
SELECT * FROM TABLE_NAME WHERE ROWID = (SELECT MIN(ROWID) FROM TABLE_NAME)
You are trying to get the one with minimal age, so I suggest you to use the Min sql built-in function:
SELECT name, Min(age)
FROM donates, persons
WHERE name = donor
AND name IN (SELECT receiver FROM donates)
It is a good practice to avoid rownum. And here you get a more semantic and efficient query.
Hope it helps,
Regards

Getting Number of records in oracle

Am trying to fetch the number of records in the table using Count(*) along with my query condition
Sample Table is
Table: STUD_NAME
Id Name
1 Steven
2 smith
2 Ben
1 Willy
My query is
select std.name
from STUD_Name where id='2'
for this it will display the output as "Smith" and "Ben", along with i need the total number of records in the STUD_NAME table.
By right it should display the total records as "4", please help me out to solve this issue and how to form the query in this case
SELECT name,
cnt as total_count
FROM (
SELECT id
name,
count(*) over () as cnt
FROM stud_name
) t
WHERE id = 2
Assuming that id is a numeric column the single quotes around the value 2 are not needed (and are actually harmful due to the implicit data type conversion that happens in the background)
What about:
select
std.name
,(select count(1) from STUD_Name) nrofstds
from STUD_Name std where std.id='2'
select STUD_NAME.name, CNT.count
from STUD_NAME
, (select count(*) COUNT from STUD_NAME) CNT
where id='2'

SQL - counting WHERE AGGREGATE>1 [duplicate]

This question already has answers here:
SQL - WHERE AGGREGATE>1
(3 answers)
Closed 9 years ago.
Imagine I have a db table of Customers containing {id,username,firstname,lastname}
If I want to find how many instances there are of different firstnames I can do:
select firstname, count(*) from Customers group by 2 order by 1;
firstname | count(*)
====================
bob | 1
jeff | 2
adam | 5
How do I count the number of firstnames that occur more than once? In pseudo-sql it would be something like:
select
COUNT(
firstname,
count(*) as num_occurrences
)
from
Customers
group by 2
having num_occurrences > 1;
You have the right idea:
SELECT COUNT(*)
FROM (
SELECT firstname
FROM Customers
GROUP BY firstname
HAVING COUNT(*) >= 2
)
The subquery counts the first names that have occurred more than once. Then you count all of those first names. The HAVING clause allows you to filter by aggregates. It's like a WHERE clause, except you can use aggregate functions.
There is no need for a subquery.
Try:
SELECT firstname, COUNT(*)
FROM Customers
GROUP BY firstname
HAVING COUNT(*) > 1
ORDER BY firstname
Or, order by the most represented name:
SELECT firstname, COUNT(*) AS custcount
FROM Customers
GROUP BY firstname
HAVING COUNT(*) > 1
ORDER BY custcount DESC;
This would do it:
select count(username)
from (select username
from Customers
group by username
having count(*) > 1);