0

I try to get all the years in a table with 174 rows. There is two differents years 2016 and 2017. And add to the query's response and Id which correspond at the "row count" of the response.

Here is the query :

SET @n=0;
SELECT YEAR (`Date`) AS Libelle, @n := @n + 1 AS id FROM Datas GROUP by Libelle

The response is :

|Libelle| Id|
|   2016|  1|
|   2017|174|   

What's the way to get :

|Libelle| Id|
|   2016|  1|
|   2017|  2| 

174 corresponds to the last record in my table. And I understand that's @n is incremented with all other rows.

Have you an idea to do this ?

2 Answers 2

1

try this. so the counter works only on the result:

SELECT  @n := @n + 1 AS id , tmp.*
FROM (
  SELECT DISTINCT YEAR (`Date`) AS Libelle FROM Datas GROUP by Libelle ) AS tmp,
  ( SELECT  @n := 0) as parameter;
Sign up to request clarification or add additional context in comments.

1 Comment

It says that there is an error in the last line "(@n :=0) as parameter"
0

Something like this perhaps?

SELECT
    t1.Libelle,
    @n := @n + 1 AS id
FROM (
    SELECT DISTINCT YEAR(`Date`) AS Libelle
    FROM Datas
    GROUP BY Libelle
) t1,
(
    SELECT @n := 0
) t2;

Related: https://stackoverflow.com/a/4474389/4152813

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.