0

I need to create a query that answers the following question:

I want to return the number of registrations that has a reading date of 26 days, number of entries that has a reading date of 27 days and there goes up to 31 days, the last 6 months. I need you to stay like this:

My expected output is this:

LOCALE   COMPETENCE    Reading_date(DAYS)     INSCRIPTION (Quantity)
------    ----         ----------             ---------
CEARA    JAN18          26                      20
CEARA    JAN18          27                      02
CEARA    JAN18          28                      34
CEARA    JAN18          29                      07
CEARA    JAN18          30                      12
CEARA    JAN18          31                      11
CEARA    FEV18          26                      21
CEARA    FEV18          27                      09

(and go...)

But my table is this:

INSCRIP  COMPETENCE     Reading_date
00183938    201801      2018-01-02
00183938    201802      2018-02-01
00183946    201709      2017-09-01
00183946    201710      2017-10-01
00183946    201711      2017-11-01

My sql that I'm trying is this (please abstract the joins):

select top 10   LOCALE
               , COMPETENCE
               , lead(Reading_date, 1) over (PARTITION by Reading_date ORDER BY Reading_date) next_lecture
               , datediff(day, Reading_date, next_lecture) Reading_date
               , INSCRIPTION
from BASE o
join LOCALE l
on u.localidade = l.cod_localidade
group by LOCALE, COMPETENCE, Reading_date, INSCRIPTION

somebody help me please? Thanks and sorry for bad english

Elton Santos
  • 571
  • 6
  • 32
  • 1
    I don't understand the source data and desired results. Can you fix the question? And explain how you calculate reading days, because it does not appear to be based solely on the reading date in one row. – Gordon Linoff Mar 20 '18 at 12:42
  • For calculate I use datediff, but is here the problem =/ – Elton Santos Mar 20 '18 at 12:44
  • 1
    I believe the problem is here: `datediff(day, Reading_date, **next_lecture**)` (the part between the asterisks). You're trying to reference another field in your `SELECT` by it's alias; you can't do that. You have to provide the full expression. When you get an error and you post a question, always provide the error in your post; otherwise you just end up with people trying to help you not understanding, or having to play "the guessing game" (as I have done here). – Thom A Mar 20 '18 at 12:54
  • I'm so sorry, the error is: Mensagem 207, Nível 16, Estado 1, Linha 27 Nome de coluna 'next_lecture' inválido. – Elton Santos Mar 20 '18 at 13:11
  • You cannot use the next_lecture column if it is not contained in either an aggregate function or in the group by clause – holder Mar 20 '18 at 14:14
  • @holder that error translates to `Message 207, Level 16, State 1, Line 27 Invalid column name 'next_lecture'.`. If the problem was it missing from the `GROUP BY` the (English) error would be along the lines of: `Msg 8120, Level 16, State 1, Line 27 Column 'next_lecture' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.` – Thom A Mar 20 '18 at 14:21
  • @larnu Yes you're correct, I missed that.. Thought it was a column in one of his tables and was confused by the spanish error message.. :) – holder Mar 20 '18 at 14:24

1 Answers1

1

I made the comment, but I'll post it as an answer as well. The error is pretty self explanatory:

Message 207, Level 16, State 1, Line 27 Invalid column name 'next_lecture'.

There is no column, next_lecture in your table. That's because, like I said in the comment:

You're trying to reference another field in your SELECT by it's alias; you can't do that.

The only place you can refer to a field by it's alias within the query itself (so not outside of it, for example when using a subquery) is within the ORDER BY clause; anywhere else will result in an error. So, a simple statement like this will fail:

SELECT 1 + 1 AS Two, Two * 2 AS Four;

You have to provide the full expression, thus:

SELECT 1 + 1 AS Two, (1 + 1) * 2 AS Four;    

As a result your query becomes:

SELECT DISTINCT TOP 10
       LOCALE,
       COMPETENCE
       LEAD(Reading_date, 1) OVER (PARTITION by Reading_date ORDER BY Reading_date) AS next_lecture
       DATEDIFF(DAY, Reading_date, LEAD(Reading_date, 1) OVER (PARTITION by Reading_date ORDER BY Reading_date)) Reading_date
       INSCRIPTION
FROM BASE o
     JOIN LOCALE l ON u.localidade = l.cod_localidade;

Note I have also remvoed the GROUP BY and used DISTINCT. You have no aggregate functions in your query, so I assume that is what you're trying to do with the use of it.

Edit: Random guess of what the OP wants, but it doesn't get there. I've added this for their reference, however, things are too unclear still:

WITH VTE AS (
    SELECT INSCRIP,COMPETENCE,CONVERT(date,reading_date) AS Reading_date
    FROM (VALUES('00183938',201801,'20180102'),
                ('00183938',201802,'20180201'),
                ('00183946',201709,'20170901'),
                ('00183946',201710,'20171001'),
                ('00183946',201711,'20171101')) V(INSCRIP,COMPETENCE,reading_date))
SELECT COMPETENCE,
       LEAD(Reading_Date) OVER (/*PARTITION BY LOCALE*/ ORDER BY Reading_Date) AS next_lecture,
       DATEDIFF(DAY,Reading_date, LEAD(Reading_Date) OVER (/*PARTITION BY LOCALE*/ ORDER BY Reading_Date)) AS ReadingDate,
       INSCRIP
FROM VTE
ORDER BY Reading_date ASC
Thom A
  • 88,727
  • 11
  • 45
  • 75
  • Dont work... Can I create a new question in portuguese or edit all this explain exactly what I want? – Elton Santos Mar 20 '18 at 17:26
  • "don't work" why doesn't it? And yes, there is also a Stackoverflow site for Portuguese users. – Thom A Mar 20 '18 at 18:51
  • But I dont post nothing in Stackoverflow portuguese, because haven't response there. I prefer here, although I have difficulty. I'll edit my question to show what happened – Elton Santos Mar 20 '18 at 19:05
  • "I don't post nothing" is a double negative, that would mean you do post something. :) – Thom A Mar 20 '18 at 20:54
  • kkkkkkk, Can you continue help me? This is the link in portuguese: https://pt.stackoverflow.com/questions/285473/usar-lead-para-pegar-a-pr%C3%B3xima-data – Elton Santos Mar 21 '18 at 05:34
  • @EltonSantos I don't speak Portuguese I'm afraid. I can help you here, however, you're yet to explain what "don't work" means. – Thom A Mar 21 '18 at 08:56
  • dont work mean that the query returned the zeros and did not work as you would. Man, I am also afraid too, if I do not resolve this query until Friday I must lose my job :( – Elton Santos Mar 21 '18 at 11:05
  • Only way I can help further is if you post your expected output in your question; at least then I know what I'm aiming for. – Thom A Mar 21 '18 at 12:31
  • Already, I edited and put my expected output. Thanks very much! – Elton Santos Mar 21 '18 at 12:54
  • @EltonSantos In your expected data you have the column `LOCALE`, however, that isn't in your sample data (it only has 3 columns). That expected output is not representative of that sample data. Unfortuantely the logic is very unclear as well. I've added a query I tried, but i get results that are nothing like your expected result. Honestly though 9and I don't mean to offend) why are you relying on someone on the internet to help you keep your job? If you need a anonymous volunteer to help you keep your job, are you really in the right career? – Thom A Mar 21 '18 at 14:49
  • Actually, the problem is why I can not express myself well in English. So it's confusing for you, but I think it's not really complicated, I'm sure not, the difficulty lies in not being able to pass on to you = / – Elton Santos Mar 21 '18 at 14:58
  • I will do the following: I will put as clear as possible in English and the names of the tables and columns I will keep in Portuguese, okay? I'm sure this way you and everyone else will understand – Elton Santos Mar 21 '18 at 14:59