Richard
Richard

Reputation: 137

T sql order by 2 rows according to different dates

I have table called "customers"

customers table has below columns

CompanyName varchar(100)    
ProductName varchar(100)    
CreatedDate datetime    
Salesprice money 

I have below data in customer table

CompanyName (column) - ProductName (column)  -  CreatedDate (column) -   Salesprice (column)
A                      B                        2015-01-02 00:00:00.000  419,10      
C                      D                        2014-04-20 00:00:00.000  30,10       
A                      B                        2014-01-02 00:00:00.000  60,00       
C                      D                        2015-04-20 00:00:00.000  540,00     

I want to select data as below. I need to order by CreatedDate from less than more like

CreatedDate 2014

CreatedDate 2015

CreatedDate 2014

CreatedDate 2015

Result must be as below (2014-2015 ordering)

A                      B                  2014-01-02 00:00:00.000  60,00  (This is 2014)
A                      B                  2015-01-02 00:00:00.000  419,10 (This is 2015)    
C                      D                  2014-04-20 00:00:00.000  30,10  (This is 2014)  
C                      D                  2015-04-20 00:00:00.000  540,00 (This is 2015)

Question:

How can i select customer table

First 2014 date than 2015 date if exists more then 2016 etc.. if CompanyName is same and ProductName is Same like Result in above side ?

Upvotes: 2

Views: 98

Answers (1)

Darian
Darian

Reputation: 348

What you need to do is add ORDER BY in your query.

SELECT * from customers
ORDER BY CompanyName, ProductName, CreatedDate;

UPDATED:

SELECT  CompanyName, ProductName, CreatedDate, ROW_NUMBER() OVER (PARTITION BY YEAR(CreatedDate) 
                                  ORDER BY YEAR(CreatedDate)) as rownumber
FROM    customers
ORDER by rownumber, YEAR(CreatedDate)

Upvotes: 4

Related Questions