How do I get difference days in SQL Server? - sql-server

I'm facing a problem that I don't know how to solve.
I would like to get difference of 3 days between 2 values. But when I do a query filter one value, i got results:
SELECT
BeginRange, EndRange,
DATEDIFF(DAY,InicioRange , FimRange ) as DifferenceDays,
Code
FROM
(SELECT
MAX(DataTransacao) OVER (ORDER BY DataTransacao) BeginRange,
LEAD(DataTransacao) OVER (ORDER BY DataTransacao) EndRange,
Code
FROM
#Relatorio1
WHERE
Code = '000008480700001') AS C
WHERE
c.EndRange > c.BeginRange
-- AND datediff(day,BeginRange, EndRange) >= 3
ORDER BY
DifferenceDays, Code
Results:
BeginRange EndRange DifferenceDays Code
-------------------------------------------------------
20170601 20170602 1 000008480700001
20170602 20170605 3 000008480700001
But when I run query without filter, I don't get the results above.
SELECT
BeginRange, EndRange,
DATEDIFF(DAY,InicioRange , FimRange ) as DifferenceDays,
Code
FROM
(SELECT
MAX(DataTransacao) OVER (ORDER BY DataTransacao) BeginRange,
LEAD(DataTransacao) OVER (ORDER BY DataTransacao) EndRange,
Code
FROM
#Relatorio1) AS C
WHERE
c.EndRange > c.BeginRange
-- AND datediff(day,BeginRange, EndRange) >= 3
ORDER BY
DifferenceDays, Code;
Results
NOTHING
What am I doing wrong? I can't get the first result that I got in first query.

Your question is a bit hard to follow, but I think you just need partition by:
SELECT BeginRange, EndRange,
DATEDIFF(DAY,InicioRange , FimRange ) as DifferenceDays
Code
FROM (SELECT MAX(DataTransacao) OVER (PARTITION BY Code ORDER BY DataTransacao) as BeginRange,
LEAD(DataTransacao) OVER (PARTITION BY Code ORDER BY DataTransacao) as EndRange,
Code
FROM #Relatorio1
) C
WHERE c.EndRange > c.BeginRange
-- AND datediff(day,BeginRange, EndRange) >= 3
ORDER BY DifferenceDays, Code;

Related

My SQL query runs perfectly, but when I add the CTE function, I get an error

My SQL query runs perfectly, but when I add the CTE function, I get an error
Please check this code and let me know what's wrong with the CTE:
WITH Consumption_details(UnitId, consumption, monthof, yearof) AS
(
SELECT
UnitId, SUM(consumption) AS consumption,
monthof, yearof
FROM
(SELECT
UnitId, apartment_consumption,
DATEPART(MONTH, day) AS monthof,
DATEPART(YEAR,day) AS yearof
FROM
MeterReading) AS t
GROUP BY
yearof, monthof, UnitId
HAVING
monthof = 2 AND yearof = 2022
ORDER BY
UnitID
)
You can't have ORDER BY inside the CTE (unless you also include TOP, which you shouldn't do in this case), and you need to do something with the CTE - it's just an expression, not a query on its own.
;;;/*be safe!*/;;;With cd(SonnenUnitId, consumption, monthof, yearof) AS
(
SELECT SonnenUnitId, ...
...
GROUP BY yearof, monthof, SonnenUnitId
HAVING monthof =2 and yearof =2022
)
SELECT * FROM cd Order by SonnenUnitID;
As an aside, this query could be a whole lot more efficient with no need for a CTE and a subquery, any of the HAVING, and the scan potentially becoming a seek.
DECLARE #mo int = 2, #yo int = 2022;
DECLARE #m date = DATEFROMPARTS(#yo, #mo, 1);
SELECT SonnenUnitId,
SUM(apartment_consumption) AS consumption,
monthof = #mo,
yearof = #yo
FROM dbo.SonnenMeterReading
WHERE [day] >= #m
AND [day] < DATEADD(MONTH, 1, #m)
GROUP BY SonnenUnitId
ORDER BY SonnenUnitId;

Internal SQL error (000603 (XX000)) due to 300010:2077141494

I am getting the following error in dbt, using snowflake and I can't figure out what the issue is.
Database Error in model stg_bank_balances2 (models/staging/cas/vpapay/finance/stg_bank_balances.sql)
000603 (XX000): SQL execution internal error:
Processing aborted due to error 300010:2077141494; incident 5570604.
compiled SQL at target/run/cas_datawarehouse/staging/cas/vpapay/finance/stg_bank_balances.sql
I have a staging table that is running 100% when I open the file and run it manually.
However when I run it with
dbt run --models +stg_bank_balances
then I get this error... any ideas?
Compiled SQL code:
with
__dbt__CTE__dw_bank_balance_base as (
with
source as (select * from CAS_RAW.BANK_BALANCE_INFORMATION_FOR_DATAWAREHOUSE.FACILITY_DATA),
renamed as (
select
to_date(date) as date
,FACILITY_BALANCE as facility_balance
,FACILITY_LIMIT as facility_limit
,LVR as loan_to_value_ratio_expected
,UNENCUMBERED_CASH as unencumbered_cash
from source
)
select *
from renamed
),data_sheet as ( select *
,row_number() over (order by date) as row_num
from __dbt__CTE__dw_bank_balance_base
),
calendar as ( select *
from ANALYTICS.dev_avanwyk.stg_calendar
where date >= (select min(date) from data_sheet)
and date <= current_date()
),
creating_leads as (
select a.*
,a.date as date_from
,case
when b.date is null then current_date()
else b.date
end as date_to
from data_sheet a
left join data_sheet b on a.row_num = b.row_num-1
),
renamed as (
select cal.date as cal_date
,ds.date_from, ds.date_to
,ds.facility_balance
,ds.facility_limit
,ds.loan_to_value_ratio_expected
,ds.unencumbered_cash
from calendar cal
left join creating_leads ds on
ds.date_from <= cal.date
and
cal.date < ds.date_to
)
select *
from renamed
Your cte names are the same, try using in your models unique cte (common table expression) names. You can see you are referencing twice a cte called "renamed". Try changing this and write back what is Snowflake spitting out.
I think Mincho is right.
The first thing to note is that this is a Database Error (docs) — this means that Snowflake is returning the error, and dbt is just passing it on.
Here, Snowflake is having difficulty because you have two CTEs (common table expressions) with the same name — renamed. It looks like you have an upstream model named dw_bank_balance_base that is ephemeral, so it's being injected as a CTE.
You can:
Rename one of your renamed CTEs to something else
Make dw_bank_balance_base a view or table by changing the materialized config
Let me know if that fixes it!
Found the issue - dbt doesn't want me joining a table to itself.
Hence I created another CTE with the prev_row_num = row_num -1 to facilitate this.
with
__dbt__CTE__dw_bank_balance_base as (
with
source as (select * from CAS_RAW.BANK_BALANCE_INFORMATION_FOR_DATAWAREHOUSE.FACILITY_DATA),
renamed as (
select
to_date(date) as date
,FACILITY_BALANCE as facility_balance
,FACILITY_LIMIT as facility_limit
,LVR as loan_to_value_ratio_expected
,UNENCUMBERED_CASH as unencumbered_cash
from source
)
select *
from renamed
),data_sheet as ( select *
,row_number() over (order by date) as row_num
,(row_number() over (order by date))-1 as prev_row_num
from __dbt__CTE__dw_bank_balance_base
),
data_sheet1 as ( select *
,(row_number() over (order by date))-1 as prev_row_num
from __dbt__CTE__dw_bank_balance_base
),
calendar as ( select *
from ANALYTICS.dev_avanwyk.stg_calendar
where date >= (select min(date) from data_sheet)
and date <= current_date()
),
creating_leads as (
select
a.date as date_from
,a.facility_balance
,a.facility_limit
,a.loan_to_value_ratio_expected
,a.unencumbered_cash
,case
when b.date is null then current_date()
else b.date
end as date_to
from data_sheet a
left join data_sheet1 b on a.row_num = b.prev_row_num
),
staging as (
select cal.date as cal_date
,ds.date_from
, ds.date_to
,ds.facility_balance
,ds.facility_limit
,ds.loan_to_value_ratio_expected
,ds.unencumbered_cash
from calendar cal
left join creating_leads ds on
ds.date_from <= cal.date
and
cal.date < ds.date_to
)
select *
from staging

Find the latest entry amongst same number with a Dash?

We have a table that stores a list of all the quotes we have sent out.
Anytime a customer revises the quotes, the system automatically appends a -1 or -2 based on last used number.
As an example
Original Quote Number : 24545
Customer asked for a revision, the quote number is now 24545-1, after sending the quote, we now have a revision again and the Quote is 24545-2 and so on.
I want to run a SQL query that will show them their Top 20 Quotes and incase of revisions, it should show the latest revisions.
Can you please help me?
I have already written a Query that would bring me top 20 quotes for the last 10 days.
SELECT Top 20
EstimateNumber,CustName,JobDescription,TotalSellPrice,EstimateStatus,EstimateDate,CommissionTableA
FROM [Enterprise32].[dbo].[tablename1]
where EstimateDate BETWEEN DATEADD(Day, -10, getdate()) AND GETDATE() AND SalesRepCode = $id And TotalSellPrice > '5000' AND EstimateStatus = 'P'
Order By TotalSellPrice DESC
This makes some assumptions, but I think this might work. If not, sample data and expected result will be invaluable:
USE Enterprise32;
GO
WITH CTE AS(
SELECT V.EstimateNumber,
V.RevisionNumber,
TN1.CustName,
TN1.JobDescription,
TN1.TotalSellPrice,
TN1.EstimateStatus,
TN1.EstimateDate,
TN1.CommissionTableA,
ROW_NUMBER() OVER (PARTITION BY V.EstimateNumber ORDER BY V.RevisionNumber DESC) AS RN
FROM dbo.TableName1 TN1
CROSS APPLY (VALUES(NULLIF(CHARINDEX('-',TN1.EstimateNumber),0)))CI(I)
CROSS APPLY (VALUES(TRY_CONVERT(int,LEFT(TN1.EstimateNumber,ISNULL(CI.I,LEN(TN1.EstimateNumber))-1)),ISNULL(TRY_CONVERT(int,STUFF(TN1.EstimateNumber,1,CI.I,'')),0)))V(EstimateNumber,RevisionNumber)
WHERE TN1.EstimateDate BETWEEN DATEADD(Day, -10, getdate()) AND GETDATE()
AND TN1.SalesRepCode = $id
And TN1.TotalSellPrice > '5000'
AND TN1.EstimateStatus = 'P')
SELECT TOP (20)
EstimateNumber,
RevisionNumber,
CustName,
JobDescription,
TotalSellPrice,
EstimateStatus,
EstimateDate,
CommissionTableA
FROM CTE
WHERE RN = 1;
With some minor changes, it might work, As there is no data sample:
SELECT Top 20
EstimateNumber,CustName,JobDescription,TotalSellPrice,EstimateStatus,EstimateDate,CommissionTableA
FROM [dbo].[tablename1] tt
LEFT JOIN
(
--Top 20 quotes Last EstimateNumber with revision
SELECT T20.RevisionFree_EstimateNumber +
CONVERT(VARCHAR,
MAX(CONVERT(INT,
SUBSTRING(t.EstimateNumber, CHARINDEX('-', EstimateNumber)+1, LEN(EstimateNumber)-CHARINDEX('-', EstimateNumber))))) Last_EstimateNumber
FROM
(
--Top 20 quotes Original EstimateNumber
SELECT DISTINCT Top 20
TotalSellPrice
,SUBSTRING(EstimateNumber, 1, CHARINDEX('-', EstimateNumber)) RevisionFree_EstimateNumber
FROM [dbo].[tablename1]
where EstimateDate BETWEEN DATEADD(Day, -10, getdate()) AND GETDATE() And TotalSellPrice > '5000' AND EstimateStatus = 'P'
Order By TotalSellPrice DESC
)AS T20
LEFT JOIN
(
SELECT *, SUBSTRING(EstimateNumber, 1, CHARINDEX('-', EstimateNumber)) RevisionFree_EstimateNumber
FROM [dbo].[tablename1]
) t
ON T20.RevisionFree_EstimateNumber = t.RevisionFree_EstimateNumber
GROUP BY T20.RevisionFree_EstimateNumber
)LastEN
ON tt.EstimateNumber = LastEN.Last_EstimateNumber

Why does order by clause doesn't work as expected when using with joins and inner query

Below is the query i tried running, it gives the correct output except that its order by is not working? I would like to order by fiscal_week first and then by region. Can any one help me out?
select 'CPD' as LOB,b.region, [FISC_WEEK_VAL], count(distinct a.qte_num_val) CPD_Qte_cnt into CPD_Qte_cnt_CQ_tog
from
(
select a.[SUB_ACCT_ID], a.qte_num_val, SnP_LOB_Lvl_1, SnP_LOB_Lvl_3, SnP_LOB_Lvl_6, [FISC_WEEK_VAL],[Converted_Flag]
,row_number() over (partition by a.[SUB_ACCT_ID], SnP_LOB_Lvl_6 order by [QUOTE_CREATE_DATE] desc, qte_num_val desc) as rownbr
from EAP_Global..[tbl_Quotes_Snp_AMER] a
where [FISC_QTR_VAL] = '2020-Q1' and [FISC_WEEK_VAL] <'2020-W05' and country='US' and SnP_LOB_Lvl_1 in ('Client Peripherals','Displays') and a.[SUB_ACCT_ID] is not null
and LOB_DESC in ('CLIENT PERIPHERALS','Displays','Precision Desktops','Latitude','Precision Notebooks','OptiPlex Desktops')
group by a.[SUB_ACCT_ID], a.qte_num_val, SnP_LOB_Lvl_1, SnP_LOB_Lvl_3, SnP_LOB_Lvl_6,[QUOTE_CREATE_DATE],[FISC_WEEK_VAL],[Converted_Flag]
)a
inner join EAP_EUC_NA..MD_SR_info_direct_indirect b on a.[SUB_ACCT_ID]=b.account_id
where region is not NULL and rownbr=1
group by b.region, [FISC_WEEK_VAL]
order by 3,2

How to pivot and get total amount each month

I have data like :
My table
My final results should be like this:
My SQL Statement:
SELECT 'Q'+cast([Month_Quarter] as varchar) Month_Quarter,COALESCE([Zugänge],0) Zugänge,COALESCE([Abgänge],0) Abgänge
FROM
(
SELECT DATEPART(QUARTER,[Monat]) [Month_Quarter],
[Zu-, Abgang],
Count(DISTINCT [Projektdefinition DB]) NoProjects
FROM AbZugänge
GROUP BY DATEPART(QUARTER,[Monat]), [Zu-, Abgang]
) proj
PIVOT (SUM(NoProjects) FOR [Zu-, Abgang] IN (Zugänge, Abgänge)) As pvt
WHERE [Month_Quarter] is not null
ORDER BY Month_Quarter
BUT with this statement I am getting the results without the Amount column Zugang and column Abgang:
How can I edit the statement to get the aggregation amount columns?
I suppose you can just wrap your query inside another select statement, then use GROUP BY. Something like this:
SELECT Month, SUM(ISNULL(column_name,0))
FROM (Your Query in here)
GROUP BY Month
Not sure I understand the point of the PIVOT in your original query. This looks like a typical aggregate is all that is required. See if this is what you need.
SELECT DATENAME(MONTH,Monat) [Month]
, sum(case when [Zu-, Abgang] = 'Zugänge' then [Zu-, Abgang] else 0 end) as Zugänge
, SUM(case when [Zu-, Abgang] = 'Abgänge' then [Zu-, Abgang] else 0 end) as Abgänge
, SUM([GWU aktuell]) as [GWU Total]
, SUM([GWU Planung aktuell]) AS [Plan Total]
, COUNT(DISTINCT [Projektdefinition DB]) NoProjects
FROM AbZugänge
group by DATENAME(MONTH,Monat)

Resources