I need to select records that are a week or less in age, by this column: dbo.mod_employmentAppProfile.dateSubmitted
Note, the #arguments.departmentID# is a coldfusion tag.
Here's my query:
SELECT
dbo.pro_Profile.profileID,
dbo.pro_Profile.firstName,
dbo.pro_Profile.lastName,
dbo.pro_Profile.isDeleted,
dbo.pro_Email.emailAddress,
dbo.mod_employmentAppJobTitles.supervisorID,
dbo.mod_employmentAppJobs.appID,
dbo.mod_employmentAppJobs.isRejected,
dbo.mod_employmentAppJobs.isDeleted AS isDeletedJobs,
dbo.mod_employmentAppJobs.emailSent,
dbo.mod_employmentAppProfile.dateAvailable,
dbo.mod_employmentAppProfile.dateSubmitted,
dbo.mod_employmentAppProfile.firstName AS appFirstName,
dbo.mod_employmentAppProfile.lastName AS appLastName,
dbo.mod_employmentAppJobTitles.title,
dbo.mod_employmentAppProfile.name,
dbo.mod_employmentAppProfile.phone,
dbo.mod_employmentAppProfile.major,
dbo.mod_employmentAppProfile.minor
FROM dbo.pro_Email
INNER JOIN dbo.pro_Profile
ON dbo.pro_Email.profileID = dbo.pro_Profile.profileID
INNER JOIN dbo.mod_employmentAppJobs
INNER JOIN dbo.mod_employmentAppJobTitles
ON dbo.mod_employmentAppJobs.jobTitleID = dbo.mod_employmentAppJobTitles.jobTitleID
INNER JOIN dbo.mod_employmentAppProfile
ON dbo.mod_employmentAppJobs.eAppID = dbo.mod_employmentAppProfile.eAppID
ON dbo.pro_Profile.profileID = dbo.mod_employmentAppJobTitles.supervisorID
WHERE (dbo.mod_employmentAppJobs.emailSent = 0)
AND (dbo.mod_employmentAppJobTitles.departmentID = #arguments.departmentID#)
AND (dbo.mod_employmentAppJobs.isRejected = 0)
I did try something like:
and (dbo.mod_employmentAppProfile.dateSubmitted < DATEADD(day, - 7, GETDATE()))
which returns no results.
Suggestions?
try
(dbo.mod_employmentAppProfile.dateSubmitted > DATEADD(day, -7, GETDATE()))
Related
There is one specific date that I do not want to include in this which is "04/08/2020". I want to filter all the records from the beginning of the year till now but not 04/08/2020. How can I do that?
SELECT
dbo.PID_RespiratorFit.PTIDNum,
rtrim(acp.LastName) + ', ' + rtrim(acp.FirstName) AS Name,
acp.BadgeID AS ID,
dbo.Patient.PcFLD01 as Organization,
dbo.PID_RespiratorFit.Risk AS Exposure,
UPPER(dbo.PID_RespiratorFit.Type) AS Mask_Type,
dbo.PID_RespiratorFit.OHSNotes AS Comments,
dbo.PID_RespiratorFit.MedicallyClearedDate AS Medically_Cleared,
dbo.PID_RespiratorFit.TrainingCompletedDate,
dbo.PID_RespiratorFit.DateIssued AS N95_Fittest_Completed,
dbo.PID_RespiratorFit.Mask AS N95_respirator,
dbo.PID_RespiratorFit.PAPR,
dbo.PID_RespiratorFit.PaprFitTestDate AS PAPR_Fittest_Completed,
dbo.PID_RespiratorFit.Active,
DATEADD(year, 1, dbo.PID_RespiratorFit.MedicallyClearedDate) AS Compliant_Through
FROM dbo.PID_RespiratorFit LEFT JOIN
dbo.Patient ON dbo.PID_RespiratorFit.PTIDNum = dbo.Patient.PTIDNUM LEFT JOIN
dbo.aspnet_CustomProfile acp ON dbo.Patient.PGuid = acp.UserId
WHERE (dbo.PID_RespiratorFit.DateIssued BETWEEN '1-1-2020' AND Getdate())
Use standard date formats! Then:
WHERE dbo.PID_RespiratorFit.DateIssued BETWEEN '2020-01-01' AND Getdate() and
dbo.PID_RespiratorFit.DateIssued <> '2020-04-08' -- or is that 2020-08-04???
If the date is really a date/time, then use:
WHERE dbo.PID_RespiratorFit.DateIssued BETWEEN '2020-01-01' AND Getdate() and
CONVERT(DATE, dbo.PID_RespiratorFit.DateIssued) <> '2020-04-08' -- or is that 2020-08-04???
I also strongly recommend table aliases so the query is much easier to write and read. For example:
SELECT . . .
FROM dbo.PID_RespiratorFit rf LEFT JOIN
dbo.Patient p
ON rf.PTIDNum = p.PTIDNUM LEFT JOIN
dbo.aspnet_CustomProfile acp
ON p.PGuid = acp.UserId
WHERE rf.DateIssued BETWEEN '2020-01-01' AND Getdate() AND
CONVERT(DATE, rf.DateIssued) <> '2020-04-08' -- or is that 2020-08-04???
You can try the below - adding an extra condition
SELECT
dbo.PID_RespiratorFit.PTIDNum,
rtrim(acp.LastName) + ', ' + rtrim(acp.FirstName) AS Name,
acp.BadgeID AS ID,
dbo.Patient.PcFLD01 as Organization,
dbo.PID_RespiratorFit.Risk AS Exposure,
UPPER(dbo.PID_RespiratorFit.Type) AS Mask_Type,
dbo.PID_RespiratorFit.OHSNotes AS Comments,
dbo.PID_RespiratorFit.MedicallyClearedDate AS Medically_Cleared,
dbo.PID_RespiratorFit.TrainingCompletedDate,
dbo.PID_RespiratorFit.DateIssued AS N95_Fittest_Completed,
dbo.PID_RespiratorFit.Mask AS N95_respirator,
dbo.PID_RespiratorFit.PAPR,
dbo.PID_RespiratorFit.PaprFitTestDate AS PAPR_Fittest_Completed,
dbo.PID_RespiratorFit.Active,
DATEADD(year, 1, dbo.PID_RespiratorFit.MedicallyClearedDate) AS Compliant_Through
FROM dbo.PID_RespiratorFit LEFT JOIN
dbo.Patient ON dbo.PID_RespiratorFit.PTIDNum = dbo.Patient.PTIDNUM LEFT JOIN
dbo.aspnet_CustomProfile acp ON dbo.Patient.PGuid = acp.UserId
WHERE (dbo.PID_RespiratorFit.DateIssued BETWEEN '1-1-2020' AND Getdate())
AND cast(dbo.PID_RespiratorFit.DateIssued as date)<>'2020-04-08'
What is the best way to select data from the previous week? The below returns a syntax error.
SELECT
COUNT(dbo.Calls.kbpCallID) NoofoutboundCalls
FROM (((dbo.Calls LEFT OUTER JOIN dbo.OrganizationContacts ON dbo.Calls.kbpOrganizationID = dbo.OrganizationContacts.cmcOrganizationID AND dbo.Calls.KbplocationID = dbo.OrganizationContacts.cmclocationID AND dbo.Calls.kbpcontactid = dbo.OrganizationContacts.cmccontactid)
LEFT OUTER JOIN dbo.OrganizationLocations ON dbo.OrganizationContacts.cmcOrganizationID = dbo.OrganizationLocations.cmlOrganizationID AND dbo.OrganizationContacts.cmclocationId = dbo.OrganizationLocations.cmllocationid AND dbo.OrganizationContacts.cmccontactid = dbo.organizationlocations.cmlapinvoicecontactid)
LEFT OUTER JOIN dbo.Organizations ON dbo.Calls.kbpOrganizationID = dbo.Organizations.cmoOrganizationID) * *
WHERE dbo.Calls.kbpOpenedDate = DATEADD(week, - 1,) * * AND (dbo.Organizations.cmoCustomerStatus = 1 OR dbo.Organizations.cmoCustomerStatus = 2) AND dbo.Calls.kbpCallTypeID = 'SALOB'
You haven't completed the syntax for the DATEADD function.
DATEADD requires 3 parameters:
The grain of the function - in your case WEEK
The number of intervals - in your case -1
The column that you are interacting on - in your case this is missing
As it seems to be based on the current date then I think you want that line to be:
`WHERE dbo.Calls.kbpOpenedDate = DATEADD(week, -1, GETDATE())`
However, that also is a specific date and time that you are looking for equality on. More likely you are looking for a range so you may have to use greater than instead of equals or include another DATEADD to define the start/end range along with this one.
try this way
DECLARE #startDate DATETIME= DATEADD(DAY, 2 - DATEPART(WEEKDAY, GETDATE()-7), CAST(GETDATE()-7 AS DATE))
DECLARE #endDate DATETIME= DATEADD(DAY, 8 - DATEPART(WEEKDAY, GETDATE()-7), CAST(GETDATE()-7 AS DATE))
SELECT
COUNT(dbo.Calls.kbpCallID) NoofoutboundCalls
FROM (((dbo.Calls
LEFT OUTER JOIN dbo.OrganizationContacts ON dbo.Calls.kbpOrganizationID = dbo.OrganizationContacts.cmcOrganizationID and dbo.Calls.KbplocationID = dbo.OrganizationContacts.cmclocationID and dbo.Calls.kbpcontactid = dbo.OrganizationContacts.cmccontactid)
LEFT OUTER JOIN dbo.OrganizationLocations ON dbo.OrganizationContacts.cmcOrganizationID = dbo.OrganizationLocations.cmlOrganizationID and dbo.OrganizationContacts.cmclocationId = dbo.OrganizationLocations.cmllocationid and dbo.OrganizationContacts.cmccontactid = dbo.organizationlocations.cmlapinvoicecontactid)
LEFT OUTER JOIN dbo.Organizations ON dbo.Calls.kbpOrganizationID = dbo.Organizations.cmoOrganizationID)
**WHERE dbo.Calls.kbpOpenedDate BETWEEN #startDate AND #endDate**
AND (dbo.Organizations.cmoCustomerStatus = 1 OR dbo.Organizations.cmoCustomerStatus = 2)
AND dbo.Calls.kbpCallTypeID = 'SALOB'
I need some help with my SQL command. I have a VB.net application that uses few sql tables to get the final result. I need to add few additional columns from TableC into my application, but these columns are not part of GROUPBY function.
I tried to add simple select function to the code, but I always get the same error:
$"
SET NOCOUNT ON;
SELECT CONVERT(VARCHAR(10), r.PossibleDate, 120) as [Date],
**SELECT r.GStart as GStart,**
SUM(ISNULL(r.ElecCheckIn, 0)) as CheckIn,
SUM(ISNULL(r.ElecCheckOut, 0)) as CheckOut,
SUM(ISNULL(r.JPAmount, 0)) as AttAmountJP,
SUM(ISNULL(r.MeteredAttAmountCC, 0)) as AttAmountCC,
SUM(ISNULL(r.MeteredMachAmount, 0)) as MachAmount,
SUM(ISNULL(r.MeteredAttAmount, 0)) as AttAmount,
SUM(ISNULL(r.ElecCheckIn, 0) - ISNULL(r.ElecCheckOut, 0) - ISNULL(r.JPAmount, 0) - ISNULL(r.MeteredAttAmountCC, 0) - ISNULL(r.MeteredMachAmount, 0) - ISNULL(r.MeteredAttAmount, 0)) as NetWin
FROM dbo.CDS_TableA sm (NOLOCK)
INNER JOIN dbo.bb_tableB st (NOLOCK)
ON sm.TableB_Id=st.SlotB_Id
AND sm.TableBRevision=st.TabelBRevision
INNER JOIN dbo.TableC r (NOLOCK)
ON sm.TableA_ID=r.TableA_ID
AND r.PossibleDate BETWEEN '{dtStart.Value.ToString("yyyy-MM-dd")} 00:00:00' AND '{dtEnd.Value.ToString("yyyy-MM-dd")} 23:59:59'
AND r.Period_ID=4
INNER JOIN dbo.BB_TableD rh (NOLOCK)
ON sm.TableA_ID=rh.TableA_ID
AND r.PossibleDate=rh.PossibleDate
AND sm.Revision=rh.Revision
WHERE sm.OnFloorFlag = 1
AND sm.Calc_ID NOT IN (2,5)
GROUP BY r.PossibleDate
ORDER BY r.PossibleDate;
I always get an error that GStart is not contained in either an aggregate function or the GROUP BY clause.
Simply JOIN the aggregate level to unit level which can be facilitated with a CTE. Run this entire statement below including WITH clause.
WITH agg AS (
SELECT CONVERT(VARCHAR(10), r.PossibleDate, 120) as [Date],
SUM(ISNULL(r.ElecCheckIn, 0)) as CheckIn,
SUM(ISNULL(r.ElecCheckOut, 0)) as CheckOut,
SUM(ISNULL(r.JPAmount, 0)) as AttAmountJP,
SUM(ISNULL(r.MeteredAttAmountCC, 0)) as AttAmountCC,
SUM(ISNULL(r.MeteredMachAmount, 0)) as MachAmount,
SUM(ISNULL(r.MeteredAttAmount, 0)) as AttAmount,
SUM(ISNULL(r.ElecCheckIn, 0) -
ISNULL(r.ElecCheckOut, 0) -
ISNULL(r.JPAmount, 0) -
ISNULL(r.MeteredAttAmountCC, 0) -
ISNULL(r.MeteredMachAmount, 0) -
ISNULL(r.MeteredAttAmount, 0)) as NetWin
FROM dbo.CDS_TableA sm (NOLOCK)
INNER JOIN dbo.bb_tableB st (NOLOCK)
ON sm.TableB_Id =s t.SlotB_Id
AND sm.TableBRevision=st.TabelBRevision
INNER JOIN dbo.TableC r (NOLOCK)
ON sm.TableA_ID= r.TableA_ID
AND r.PossibleDate BETWEEN '{dtStart.Value.ToString("yyyy-MM-dd")} 00:00:00'
AND '{dtEnd.Value.ToString("yyyy-MM-dd")} 23:59:59'
AND r.Period_ID=4
INNER JOIN dbo.BB_TableD rh (NOLOCK)
ON sm.TableA_ID=rh.TableA_ID
AND r.PossibleDate=rh.PossibleDate
AND sm.Revision=rh.Revision
WHERE sm.OnFloorFlag = 1
AND sm.Calc_ID NOT IN (2,5)
GROUP BY r.PossibleDate
)
SELECT r.GStart as GStart, agg.* --- ADD OTHER r FIELDS
FROM dbo.TableC r
INNER JOIN agg ON CONVERT(VARCHAR(10), r.PossibleDate, 120) = agg.[Date]
ORDER BY r.PossibleDate
Aside: While I know nothing of vb.net, I do know running SQL at application layer and your concatenation of dates above should be parameterized values which is a programming industry best practice. See How do I create a parameterized SQL query? Why Should I? Also, use NOLOCK with caution.
I'm trying to create an column in my query to show an ordered classification ( show 1, 2, 3 ( as in first, second, third ...)) relative to date... in my current query i have filtered data from the last 12 months ( as example, from 1-9-2016 to 31-8-2017)
using DATEADD(mm; DATEDIFF(m; - 1; GETDATE()) - 12; 0)
for the first date and
DATEADD(s; - 1; DATEADD(mm; DATEDIFF(m; 0; GETDATE()) + 1; 0))
for the last day of the current month. And i also have two columns, one with the month and other with the year, both extracted from a document date column present in the data ( i'm using
MONTH(dbo.Mov_Venda_Cab.dtmData) and YEAR(dbo.Mov_Venda_Cab.dtmData)).
My goal is to have a column showing something like this :
If the month is the first from the interval ( if is month 9 and year 2016 ) is has to show 1 , if is the second ( month 10 and year 2016) , show 2, all continuously until the current month ( that is 8 and year 2017) and showing 12.
If the values where static i could do a simple case and would achieve what i wanted. My problem is that since when i get the data filtered by my current date and the 12 months behind, i don't manage to get the same result because i don't know exactly what i should do in the CASE expression.
so that it could help my columns are :
Item ; Qty ; Month ; Year ; dtmData ; orderedMonth
ORIGINAL QUERY :
SELECT DISTINCT DATEADD(mm, DATEDIFF(m, - 1, GETDATE()) - 12, 0) AS DATA_INI,
DATEADD(s, - 1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0)) AS DATA_FIM,
dbo.Mov_Venda_Lin.Id,
MONTH(dbo.Mov_Venda_Cab.dtmData) AS Mes,
YEAR(dbo.Mov_Venda_Cab.dtmData) AS Ano,
dbo.Mov_Venda_Lin.fltValorMercadoriaSIVA * dbo.Mov_Venda_Cab.intSinal AS Mercadoria,
dbo.Mov_Venda_Lin.fltValorLiquido * dbo.Mov_Venda_Cab.intSinal AS ValorLiquido,
CASE
WHEN tbl_tipos_documentos.bitconsideraqtdmapas = 1
THEN (Mov_Venda_Lin.fltQuantidade * mov_venda_cab.intsinal)
ELSE 0
END AS Quantidade,
dbo.Mov_Venda_Lin.strCodSeccao AS Seccao,
dbo.Mov_Venda_Lin.strAbrevTpDoc AS TpDoc,
dbo.Tbl_Tipos_Documentos.strDescricao AS DescTpDoc,
dbo.Mov_Venda_Lin.intNumLinha AS Linha,
dbo.Mov_Venda_Lin.strCodExercicio AS Exercicio,
dbo.Mov_Venda_Cab.strAbrevMoeda AS Moeda,
dbo.Mov_Venda_Cab.fltCambio AS Cambio,
dbo.Mov_Venda_Lin.strCodArtigo AS Artigo,
dbo.Tbl_Gce_Artigos.strDescricao AS DescArtigo,
dbo.Mov_Venda_Lin.strCodClassMovStk AS MovStk,
dbo.Tbl_ClassificacaoMovStk.strDescricao AS DescMovStk,
CASE
WHEN mov_venda_cab.inttpentidade = 0
THEN tbl_gce_tipos_entidade.strcodigo
ELSE NULL
END AS TpEntidade,
CASE
WHEN mov_venda_cab.inttpentidade = 0
THEN tbl_gce_tipos_entidade.strdescricao
ELSE NULL
END AS DescTpEntidade,
CASE
WHEN mov_venda_cab.intcodentidade <> 0
THEN mov_venda_cab.intcodentidade
ELSE NULL
END AS CodEntidade,
CASE
WHEN mov_venda_cab.inttpentidade = 0
AND mov_venda_cab.intcodentidade <> 0
THEN 'Cliente'
WHEN mov_venda_cab.inttpentidade = 1
AND mov_venda_cab.intcodentidade <> 0
THEN 'Outro Devedor'
ELSE NULL
END AS TipoEntidade,
CASE
WHEN mov_venda_cab.inttpentidade = 0
THEN tbl_clientes.strnome
ELSE tbl_outros_devedores.strnome
END AS DescNome,
dbo.Tbl_SubZonas.strAbrevZona AS Zona,
dbo.Tbl_Zonas.strDescricao AS DescZona,
dbo.Mov_Venda_Cab.strAbrevSubZona AS SubZona,
dbo.Tbl_SubZonas.strDescricao AS DescSubZona,
dbo.Mov_Venda_Cab.intCodVendedor AS Vendedor,
dbo.Tbl_Gce_Vendedores.strNome AS DescNomeVend,
dbo.Tbl_Gce_Artigos.strCodCategoria AS Categoria,
dbo.Tbl_Gce_Categorias.strDescricao AS DescCategoria,
dbo.Tbl_Gce_Artigos.strTpArtigo AS TpArtigo,
dbo.Tbl_Gce_Tipos_Artigos.strDescricao AS DescTpArtigo,
CAST(NULL AS VARCHAR(13)) AS CodFamiliaAgrup,
CAST(NULL AS VARCHAR(35)) AS DescFamAgrup,
CAST(NULL AS VARCHAR(13)) AS CodFamiliaRes,
CAST(NULL AS VARCHAR(35)) AS DescFamRes,
dbo.Mov_Venda_Cab.strForteAbrevMoeda AS abrevmoeda,
dbo.Mov_Venda_Cab.fltForteCambio AS fortecambio
FROM dbo.Mov_Venda_Lin WITH (NOLOCK)
LEFT OUTER JOIN dbo.Mov_Venda_Cab WITH (NOLOCK)
ON dbo.Mov_Venda_Lin.strCodSeccao = dbo.Mov_Venda_Cab.strCodSeccao
AND dbo.Mov_Venda_Lin.strAbrevTpDoc = dbo.Mov_Venda_Cab.strAbrevTpDoc
AND dbo.Mov_Venda_Lin.strCodExercicio = dbo.Mov_Venda_Cab.strCodExercicio
AND dbo.Mov_Venda_Lin.intNumero = dbo.Mov_Venda_Cab.intNumero
LEFT OUTER JOIN dbo.Tbl_Gce_Armazens WITH (NOLOCK)
ON dbo.Mov_Venda_Lin.strCodArmazem = dbo.Tbl_Gce_Armazens.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Artigos WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strCodigo = dbo.Mov_Venda_Lin.strCodArtigo
LEFT OUTER JOIN dbo.Tbl_Gce_ArtigosFamilias WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strCodigo = dbo.Tbl_Gce_ArtigosFamilias.strCodArtigo
LEFT OUTER JOIN dbo.Tbl_Gce_Familias WITH (NOLOCK)
ON dbo.Tbl_Gce_ArtigosFamilias.strCodFamilia = dbo.Tbl_Gce_Familias.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_ArtigosReferencias WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strCodigo = dbo.Tbl_Gce_ArtigosReferencias.strCodArtigo
LEFT OUTER JOIN dbo.Tbl_Gce_Referencias WITH (NOLOCK)
ON dbo.Tbl_Gce_ArtigosReferencias.strCodReferencia = dbo.Tbl_Gce_Referencias.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Tipos_Artigos WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strTpArtigo = dbo.Tbl_Gce_Tipos_Artigos.strCodigo
LEFT OUTER JOIN dbo.Tbl_Clientes WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.intCodEntidade = dbo.Tbl_Clientes.intCodigo
LEFT OUTER JOIN dbo.Tbl_Direccoes WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.intCodEntidade = dbo.Tbl_Direccoes.intCodigo
AND dbo.Mov_Venda_Cab.intDireccao = dbo.Tbl_Direccoes.intNumero
AND dbo.Mov_Venda_Cab.intTpEntidade = dbo.Tbl_Direccoes.intTp_Entidade
LEFT OUTER JOIN dbo.Tbl_Outros_Devedores WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.intCodEntidade = dbo.Tbl_Outros_Devedores.intCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Vendedores WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.intCodVendedor = dbo.Tbl_Gce_Vendedores.intCodigo
LEFT OUTER JOIN dbo.Tbl_Tipos_Documentos WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.strAbrevTpDoc = dbo.Tbl_Tipos_Documentos.strAbreviatura
LEFT OUTER JOIN dbo.Tbl_SubZonas WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.strAbrevSubZona = dbo.Tbl_SubZonas.strAbreviatura
LEFT OUTER JOIN dbo.Tbl_Zonas WITH (NOLOCK)
ON dbo.Tbl_SubZonas.strAbrevZona = dbo.Tbl_Zonas.strAbreviatura
LEFT OUTER JOIN dbo.Tbl_Gce_Categorias WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strCodCategoria = dbo.Tbl_Gce_Categorias.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Seccoes WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.strCodSeccao = dbo.Tbl_Gce_Seccoes.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Tipos_Entidade WITH (NOLOCK)
ON dbo.Tbl_Clientes.strTpEntidade = dbo.Tbl_Gce_Tipos_Entidade.strCodigo
LEFT OUTER JOIN dbo.Tbl_ClassificacaoMovStk WITH (NOLOCK)
ON dbo.Mov_Venda_Lin.strCodClassMovStk = dbo.Tbl_ClassificacaoMovStk.strCodigo
WHERE (dbo.Mov_Venda_Cab.intTpEntidade = 0
OR dbo.Mov_Venda_Cab.intTpEntidade IS NULL)
AND (dbo.Mov_Venda_Cab.strAbrevTpDoc IN ('CRFCX', 'FACIV', 'FACTC', 'FCTA', 'LANIV', 'LOFX', 'LONC', 'LXANI', 'NCFCX', 'NFACC', 'NFACE', 'NFACM', 'NFACT', 'NNCRC', 'NNCRE', 'NNCRM', 'NNDEB', 'NNDEC', 'NNDEV', 'NVDIC', 'NVDIN', 'XLACC', 'XLACD'))
AND (dbo.Mov_Venda_Cab.strCodSeccao IN ('1', 'ENCT1', 'ENCT2', 'ENCT3', 'ENCT4', 'ENCT5', 'ENCT6'))
AND (dbo.Mov_Venda_Cab.dtmData > DATEADD(mm, DATEDIFF(m, - 1, GETDATE()) - 12, 0))
AND (dbo.Mov_Venda_Cab.dtmData <= DATEADD(s, - 1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0)))
AND (dbo.Mov_Venda_Lin.intTpLinha > 2)
AND (dbo.Mov_Venda_Cab.bitAnulado = 0)
AND (dbo.Mov_Venda_Cab.bitConvertido = 0)
Luckily there's a much less complicated method than using a bunch of CASE statements. You can use the ROW_NUMBER function.
First, don't split your dates into month and year. Just use Getdate() to calculate your desired range and compare your source dates to that. Then you add the ROW_NUMBER to get your ordering output:
SELECT
*
,ordered_output = (ROW_NUMBER()OVER(PARTITION BY grouping_field ORDER BY cast(dtmData as datetime) ASC))
FROM Mov_Venda_Cab
WHERE cast(dtmData as datetime) >= getdate() - 365
This example assumes your have some ID field or similar on which your want to group your output, represented by grouping_field in the example. Your results would look like:
grouping_field dtmData ordered_output
1 8/1/2017 1
1 8/2/2017 2
1 8/3/2017 3
2 8/1/2017 1
2 8/2/2017 2
2 8/3/2017 3
If you don't want to group your output, just ordering everything by the date, you can omit the PARTITION BY grouping_field text. You'd get instead something like:
dtmData ordered_output
8/1/2017 1
8/2/2017 2
8/3/2017 3
8/4/2017 4
8/5/2017 5
8/6/2017 6
EDIT: Asker clarified that all records with the same month should get the same ordered output.
To do that you first need to assign each month/year combo a rank and rejoin that to the main table using two layers of subqueries:
SELECT b.*, c.month_rank
from Mov_Venda_Cab as b
inner join
(select mnt, yr, ROW_NUMBER() OVER(ORDER BY A.yr, A.mnt) AS month_rank
from (
SELECT DISTINCT
MONTH(dtmData) as mnt
, YEAR(dtmData) as yr
from Mov_Venda_Cab
WHERE cast(dtmData as datetime) >= getdate() - 365
) as a
) as c
on MONTH(b.dtmData) = c.mnt and YEAR(b.dtmData) = c.yr
SELECT 'COUNT=' + CONVERT(VARCHAR(64), COUNT(s.company)) AS sites
FROM site s
WHERE s.sitetype = 'om'
AND s.status = 1
EXCEPT
SELECT DISTINCT sg.company
FROM snmpmibdevice AS sdevice
JOIN site sg
ON sg.guid = sdevice.siteguid
JOIN snmpmibdata sdata
ON sdata.snmpmibdeviceguid = sdevice.snmpmibdeviceguid
WHERE sdata.sampletimestamp > Dateadd (mi, -15, Getutcdate())
AND sg.sitetype = 'OM'
Basically I am attempting to return a count of company names from this. If I remove the count and just select "S.Company" I will get 2 values (I would like "COUNT=2"), but with the count it comes up as 34 records (COUNT=34).
I would appreciate any help. Thanks!
wrap the whole thing in a "select count(*) from ()"
SELECT 'COUNT=' + CONVERT(VARCHAR(64), COUNT(company)) AS sites
FROM (
SELECT s.company
FROM site s
WHERE s.sitetype = 'om'
AND s.status = 1
EXCEPT
SELECT DISTINCT sg.company
FROM snmpmibdevice AS sdevice
JOIN site sg
ON sg.guid = sdevice.siteguid
JOIN snmpmibdata sdata
ON sdata.snmpmibdeviceguid = sdevice.snmpmibdeviceguid
WHERE sdata.sampletimestamp > Dateadd (mi, -15, Getutcdate())
AND sg.sitetype = 'OM'
) a