how To Select with group by and order by clause? - sql-server-2012

I need to select from table by using group by clause and then order by clause
select id,EXID,Rate,Date,Currency from tb_exchange where Boolean='True' group by id,EXID,Rate,Date,Currency ORDER BY id DESC
But it return normally like
select * from tb_exchange where Boolean='True' ORDER BY id DESC
I need to return the newest item first and it groups by currency name. My Currency Name are (THB and USD )
Please help me,
thank in advance.

You may try using ROW_NUMBER here:
SELECT id, EXID, Rate, Date, Currency
FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY Currency ORDER BY Date DESC) rn
FROM tb_exchange
WHERE Boolean = 'True'
) t
WHERE rn = 1
ORDER BY id DESC;
This answer assumes that you want the latest record from each Currency group and that the Date column records how recent or old a given record is.

Related

Get latest record from a table based on 2 columns in hive

I want to get the latest record from my source table based on num and id columns and insert in my target table.
Scenario is explained in the attached screen shot. For latest record date column can be used.
Screenshot
Thanks.
Select num,id, date
FROM
(
Select *, ROW_NUMBER() OVER(partition by num,id Order by date desc) as rnk
FROM source_table
)a
WHERE rnk = 1;
by using corelated Subquery
select * from your_table t
where t.date= (
select max(date) from your_table t1
where t1.num=t.num and t1.id=t.id
)
You can do it using max() function
select num,id,max(date) from your_table t
group by num,id
SELECT NUM,ID,DATE FROM TABLE_TEMP
QUALIFY RANK OVER(PARTITION BY NUM,ID ORDER BY DATE DESC)=1;
You can do this using single line query
SELECT NUM,ID,DATE FROM TABLE_TEMP
QUALIFY RANK OVER(PARTITION BY NUM,ID ORDER BY DATE DESC)=1;

Insert every other row to a Column

I have this Table with one row Transaction Date the first row is the checkIn and the second one is the Checkout if we organized the result by date asc.
I need to pass the second row value to another column named Checkout. This table has at least 1000 records
Try using the query below
With CteCheckOut as(
Select
ROW_NUMBER() over (Partition by studentID Order by studentID,transactionDate) as Rownumber,
*
From student
)
Select studentID, transactionDate as CheckOutDate
From CteCheckOut
Where Rownumber%2 = 0
You can use row_number():
select t.*
from (select t.*,
row_number() over (partition by studentid order by transactiondate) as seqnum
from t
) t
where seqnum = 2;
This assumes that only studentid is used to identify the "first" and "second" rows. If more columns are needed, add them to the partition by clause.
If the checkout date you need is the second (max) date grouped by reason and you want to single out this date then try:
select
studentID,
reason,
max(transactionDate) as checkoutDate
from student
group by
reason

SQL SERVER QUERY to select max value record per item

This is the sample table
What I need to achieve is to get or display only the record of tenant with the highest month value. If ever month is equal, I need to base on the latest date value. Here is the sample desired output
With this, I started by this code using max function and incorporated temp table, but unable to get the desired result.
select tenant, name, date, month
into #sample
from tenant
select *
from #sample
where months = (select max(months)from #sample)
and output to something like this. As I believe, the code is getting the max value in the whole list not considering per tenant filtering.
Any help will be greatly appreciated :)
This can be done with the row_number window function:
select tenant, name, date, months
from (select t.*,
row_number() over (partition by t.tenant, t.name order by t.months desc, t.date desc) as rn
from TableName t) x
where rn = 1
You can use a row_number function.
Query
;with cte as
(
select rn = row_number() over
(
partition by tenant
order by months desc,[date] desc
),*
from table_name
)
select tenant,name,[date],months from cte
where rn = 1;

how to get the distinct records based on maximum date?

I'm working with Sql server 2008.i have a table contains following columns,
Id,
Name,
Date
this table contains more than one record for same id.i want to get distinct id having maximum date.how can i write sql query for this?
Use the ROW_NUMBER() function and PARTITION BY clause. Something like this:
SELECT Id, Name, Date FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Date desc) AS ROWNUM
FROM [MyTable]
) x WHERE ROWNUM = 1
If you need only ID column and other columns are NOT required, then you don't need to go with ROW_NUMBER or MAX or anything else. You just do a Group By over ID column, because whatever the maximum date is you will get same ID.
SELECT ID FROM table GROUP BY ID
--OR
SELECT DISTINCT ID FROM table
If you need ID and Date columns with maximum date, then simply do a Group By on ID column and select the Max Date.
SELECT ID, Max(Date) AS Date
FROM table
GROUP BY ID
If you need all the columns but 1 line having Max. date then you can go with ROW_NUMBER or MAX as mentioned in other answers.
SELECT *
FROM table AS M
WHERE Exists(
SELECT 1
FROM table
WHERE ID = M.ID
HAVING M.Date = Max(Date)
)
One way, using ROW_NUMBER:
With CTE As
(
SELECT Id, Name, Date, Rn = Row_Number() Over (Partition By Id
Order By Date DESC)
FROM dbo.TableName
)
SELECT Id --, Name, Date
FROM CTE
WHERE Rn = 1
If multiple max-dates are possible and you want all you could use DENSE_RANK instead.
Here's an overview of sql-server's ranking function: http://technet.microsoft.com/en-us/library/ms189798.aspx
By the way, CTE is a common-table-expression which is similar to a named sub-query. I'm using it to be able to filter by the row_number. This approach allows to select all columns if you want.
select Max(Date) as "Max Date"
from table
group by Id
order by Id
Try with Max(Date) and GROUP BY the other two columns (the ones with repeating data)..
SELECT ID, Max(Date) as date, Name
FROM YourTable
GROUP BY ID, Name
You may try with this
DECLARE #T TABLE(ID INT, NAME VARCHAR(50),DATE DATETIME)
INSERT INTO #T VALUES(1,'A','2014-04-20'),(1,'A','2014-04-28')
,(2,'A2','2014-04-22'),(2,'A2','2014-04-24')
,(3,'A3','2014-04-20'),(3,'A3','2014-04-28')
,(4,'A4','2014-04-28'),(4,'A4','2014-04-28')
,(5,'A5','2014-04-28'),(5,'A5','2014-04-28')
SELECT T.ID FROM #T T
WHERE T.DATE=(SELECT MAX(A.DATE)
FROM #T A
WHERE A.ID=T.ID
GROUP BY A.ID )
GROUP BY T.ID
select id, max(date) from NameOfYourTable group by id;

Select Record with Maximum Creation Date

Let us say that I have a database table with the following two records:
CACHE_ID BUSINESS_DATE CREATED_DATE
1183 13-09-06 13-09-19 16:38:59.336000000
1169 13-09-06 13-09-24 17:19:05.762000000
1152 13-09-06 13-09-17 14:18:59.336000000
1173 13-09-05 13-09-19 15:48:59.136000000
1139 13-09-05 13-09-24 12:59:05.263000000
1152 13-09-05 13-09-27 13:28:59.332000000
I need to write a query that will return the CACHE_ID for the record which has the most recent CREATED_DATE.
I am having trouble crafting such a query. I can do a GROUP BY based on BUSINESS_DATE and get the MAX(CREATED_DATE)...of course, I won't have the CACHE_ID of the record.
Could someone help with this?
Not positive on oracle syntax, but use the ROW_NUMBER() function:
SELECT BUSINESS_DATE, CACHE_ID
FROM (SELECT t.*,
ROW_NUMBER() OVER(PARTITION BY BUSINESS_DATE ORDER BY CREATED_DATE DESC) RN
FROM YourTable t
)sub
WHERE RN = 1
The ROW_NUMBER() function assigns a number to each row. PARTITION BY is optional, but used to start the numbering over for each value in that group,  ie: if you PARTITION BY BUSINESS_DATE  then for each unique BUSINESS_DATE value the numbering would start over at 1.  ORDER BY of course is used to define how the counting should go, and is required in the ROW_NUMBER() function.
You want to group on business date, and get the CACHE_ID with the most current created date? Use something like this:
select yt.CACHE_ID, yt.BUSINESS_DATE, yt.CREATED_DATE
from YourTable yt
where yt.CREATED_DATE = (select max(yt1.CREATED_DATE)
from YourTable yt1
where yt1.BUSINESS_DATE = yt.BUSINESS_DATE)
Not sure of the exact syntax, but conceptually, can't you just sort by CREATED_DATE descending and take the first one?
Across all records -
select top 1 CACHE_ID from YourTable order by CREATED_DATE desc
For each BUSINESS_DATE -
select distinct
a.BUSINESS_DATE,
(
select top 1 b.CACHE_ID
from YourTable b where a.BUSINESS_DATE = b.BUSINESS_DATE
order by b.CREATED_DATE desc
) as Last_CREATED_DATE
from YourTable a