Question

I have a problem with a SQL query on the database and greatly count on your help. The point is that I have 2 columns in any table. One of the columns contains dates and other numerical values​​. My task is adding a third column, with the numerical values ​​defining the time of origin specific numerical value - a sort of priority. If the value is present in the form of only one record, which is matched only one date should receive a value of 1 in the third column. If a particular value occurs in two records with the same date then one of these records in a 3 column should have a value of 1 and the second - with the later - the value 2 How to go about it?

What's wrong with it? It's my code:

SELECT s.id, s.value, (
  SELECT s2.value, COUNT(s2.id) FROM table s2 GROUP BY s2.value ORDER BY s2.value
 ), s.date 
 FROM table s
 GROUP BY s.value

Example: I've got two columns - one with date and another one with values. Values are unique but two or three different values could have got the same date:

Values      Dates
0.1         2005.01.01
0.1         2006.02.01
0.3         2006.12.01
0.5         2007.06.05
0.3         2007.03.01
0.3         2007.05.20

I want to add column with version of the value like this:

Values      Dates          Version
0.1         2005.01.01     1
0.1         2006.02.01     2
0.3         2006.12.01     1
0.5         2007.06.05     1
0.3         2007.03.01     2
0.3         2007.05.20     3
Was it helpful?

Solution

Taking an example from FirebirdFAQ, you could do something like:

SELECT a.column1, a.column2, COUNT(b.column1) + 1 AS "rank"
FROM theTable a
LEFT JOIN theTable b ON a.column1 = b.column1 AND b.column2 < a.column2
GROUP BY 1, 2

In the upcoming Firebird 3 you can use the windows functions like RANK() or ROW_NUMBER():

SELECT column1, column2,
   RANK() OVER (PARTITION BY column1 ORDER BY column2) AS "rank"
FROM theTable a
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top