TSql Report - sql server 2008 - sql-server

I have a report that i run every month, below is the sql script for it. My problem currently is i have to run the sql script in text format and then save the result set into a tab delimited file and then save to excel. Right now on the excel it get everything even the rows it ran. I wanted to get everything in one result set. Please help. Thanks.
declare #xmid varchar(16)
declare #locationdba varchar(100)
declare #month varchar(2)
declare #year varchar(4)
set #month = '05'
set #year = '2011'
select distinct xmid,LOCATIONDBA into #tmpMIDS
from tblmerchants a
join tblmerchantapplications b on a.merchantid = b.merchantid
where locationdba like 'farmers furniture%'
SELECT 'TOTAL FOR ALL STORES'
SELECT 'INTERCHANGE : ALL STORES'
select ledgercode,substring(cast(ledgercode as varchar),5,3) FeeClass, mrev.description, sum(cnt) cnt, sum(volume) volume, MIC.RATE,MIC.PERITEM,
--case when substring(cast(ledgercode as varchar),4,1) = 1 then 0.000950 else 0.000925 end Assessments,
TotalDisc = sum(volume)* MIC.RATE --+ sum(volume) * case when substring(cast(ledgercode as varchar),4,1) = 1 then 0.000950 else 0.000925 end,
,totalPerItem = sum(cnt) * MIC.PERITEM ,
--TotalAmt = round(sum(TotalAmount),2,1)
TotalAmt = sum(TotalAmount)
from monthendrevshare mrev
join dbo.MonthendInterchange mIC on mrev.ledgercode = (900000000 + (mic.CardType * 100000) + (ICCode * 100) + 1 ) and enddate is null
where ledgercode > 900000 and xmid in (select xmid from #tmpMIDS )
and entrymonth = #month and entryyear = #year AND ROOTPORTFOLIOACCOUNTNUMBER = '1'
group by ledgercode,mrev.description, MIC.RATE,MIC.PERITEM
having sum(volume) > 0
order by volume desc
SELECT 'CREDIT INTERCHANGE : ALL STORES'
select ledgercode, substring(cast(ledgercode as varchar),5,3) FeeClass, mrev.description, sum(cnt) cnt, sum(volume) volume, MIC.RATE,MIC.PERITEM,
--case when substring(cast(ledgercode as varchar),4,1) = 1 then 0.000950 else 0.000925 end Assessments,
TotalDisc = sum(volume)* MIC.RATE --+ sum(volume) * case when substring(cast(ledgercode as varchar),4,1) = 1 then 0.000950 else 0.000925 end,
,totalPerItem = sum(cnt) * MIC.PERITEM,
--TotalAmt = round(sum(TotalAmount),2,1)
TotalAmt = sum(TotalAmount)
from monthendrevshare mrev
join dbo.MonthendInterchange mIC on mrev.ledgercode = (900000000 + (mic.CardType * 100000) + (ICCode * 100) + 1 ) and enddate is null
where ledgercode > 900000 and xmid in ( select xmid from #tmpMIDS )
and entrymonth = #month and entryyear = #year AND ROOTPORTFOLIOACCOUNTNUMBER = '1'
group by ledgercode,mrev.description, MIC.RATE,MIC.PERITEM
having sum(volume) <= 0
order by volume
SELECT 'AUTHORIZATIONS : ALL STORES'
select ledgercode, mrev.description, sum(cnt) cnt, AVG(PERITEM) PERITEM, SUM(TOTALAMOUNT) TOTAL
from monthendrevshare mrev
where ledgergroup = 11
and ledgercode not in (30,102)
and xmid in (select xmid from #tmpMIDS)
and entrymonth = #month and entryyear = #year AND ROOTPORTFOLIOACCOUNTNUMBER = '1'
group by ledgercode,mrev.description
having SUM(TOTALAMOUNT) > 0
order by TOTAL desc
SELECT 'FEES : ALL STORES'
select ledgercode, mrev.description, sum(volume) Volume, sum(cnt) Count, AVG(RATE) RATE, AVG(PERITEM) PERITEM, SUM(TOTALAMOUNT) TOTAL
from monthendrevshare mrev
where (ledgergroup = 12 or ledgercode in (104,105,30,102,500,501,502,503,92,94) )
and ledgercode not in (33,34,46,79,47,133,48,123)
and xmid in (select xmid from #tmpMIDS)
and entrymonth = #month and entryyear = #year AND ROOTPORTFOLIOACCOUNTNUMBER = '1'
group by ledgercode,mrev.description
having SUM(TOTALAMOUNT) > 0
order by TOTAL desc
DECLARE Merchant_Cursor CURSOR FOR
select xmid,locationdba
from #tmpMIDS
OPEN Merchant_Cursor
FETCH NEXT FROM Merchant_Cursor into #XMID, #locationdba
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT 'TOTAL FOR STORE : ' + #XMID +' : ' + #locationdba
SELECT 'INTERCHANGE FOR STORE : ' + #XMID +' : ' + #locationdba
select ledgercode,substring(cast(ledgercode as varchar),5,3) FeeClass, mrev.description, sum(cnt) cnt, sum(volume) volume, MIC.RATE,MIC.PERITEM,
--case when substring(cast(ledgercode as varchar),4,1) = 1 then 0.000950 else 0.000925 end Assessments,
TotalDisc = sum(volume)* MIC.RATE --+ sum(volume) * case when substring(cast(ledgercode as varchar),4,1) = 1 then 0.000950 else 0.000925 end,
,totalPerItem = sum(cnt) * MIC.PERITEM ,
--TotalAmt = round(sum(TotalAmount),2,1)
TotalAmt = sum(TotalAmount)
from monthendrevshare mrev
join dbo.MonthendInterchange mIC on mrev.ledgercode = (900000000 + (mic.CardType * 100000) + (ICCode * 100) + 1 ) and enddate is null
where ledgercode > 900000 and xmid = #xmid
and entrymonth = #month and entryyear = #year AND ROOTPORTFOLIOACCOUNTNUMBER = '1'
group by ledgercode,mrev.description, MIC.RATE,MIC.PERITEM
having sum(volume) > 0
order by volume desc
SELECT 'CREDIT INTERCHANGE FOR STORE : ' + #XMID +' : ' + #locationdba
select ledgercode, substring(cast(ledgercode as varchar),5,3) FeeClass, mrev.description, sum(cnt) cnt, sum(volume) volume, MIC.RATE,MIC.PERITEM,
--case when substring(cast(ledgercode as varchar),4,1) = 1 then 0.000950 else 0.000925 end Assessments,
TotalDisc = sum(volume)* MIC.RATE, --+ sum(volume) * case when substring(cast(ledgercode as varchar),4,1) = 1 then 0.000950 else 0.000925 end,
totalPerItem = sum(cnt) * MIC.PERITEM,
--TotalAmt = round(sum(TotalAmount),2,1)
TotalAmt = sum(TotalAmount)
from monthendrevshare mrev
join dbo.MonthendInterchange mIC on mrev.ledgercode = (900000000 + (mic.CardType * 100000) + (ICCode * 100) + 1 ) and enddate is null
where ledgercode > 900000 and xmid = #xmid
and entrymonth = #month and entryyear = #year AND ROOTPORTFOLIOACCOUNTNUMBER = '1'
group by ledgercode,mrev.description, MIC.RATE,MIC.PERITEM
having sum(volume) <= 0
order by volume
SELECT 'AUTHORIZATIONS FOR STORE : ' + #XMID +' : ' + #locationdba
select ledgercode, mrev.description, sum(cnt) cnt, AVG(PERITEM) PERITEM, SUM(TOTALAMOUNT) TOTAL
from monthendrevshare mrev
where ledgergroup = 11
and ledgercode not in (30,102)
and xmid = #xmid
and entrymonth = #month and entryyear = #year AND ROOTPORTFOLIOACCOUNTNUMBER = '1'
group by ledgercode,mrev.description
having SUM(TOTALAMOUNT) > 0
order by TOTAL desc
SELECT 'FEES FOR STORE : ' + #XMID +' : ' + #locationdba
select ledgercode, mrev.description, sum(volume) Volume, sum(cnt) Count, AVG(RATE) RATE, AVG(PERITEM) PERITEM, SUM(TOTALAMOUNT) TOTAL
from monthendrevshare mrev
where (ledgergroup = 12 or ledgercode in (104,105,30,102,500,501,502,503,92,94) )
and ledgercode not in (33,34,46,79,47,133,48,123)
and xmid = #xmid
and entrymonth = #month and entryyear = #year AND ROOTPORTFOLIOACCOUNTNUMBER = '1'
group by ledgercode,mrev.description
having SUM(TOTALAMOUNT) > 0
order by TOTAL desc
FETCH NEXT FROM Merchant_Cursor into #XMID, #locationdba
END
CLOSE Merchant_Cursor
DEALLOCATE Merchant_Cursor
drop table #tmpMIDS

I'm not going to rewrite that entire proc, but here's a method you can employ:
1 - use SET NOCOUNT ON to disable the "xxx Rows Affected" messages.
2 - Keep your logic as is, but select into a "Results" table and at the end of the proc select the contents of "Results" as the only output. You can't really use a UNION as it is now since you have different field names. If you NEED differing field names between result sets, then you won't ever be able to merge them into one final result in a functional way.

Related

How do i escape aliases in Dynamic sql

I am getting an error near Alias Names i.e., Month_Name, Limit_Mins, Amount in this dynamic sql, how do i resolve that , i tried with adding one more quote, but when i do tyhat i am only getting #columnames into the sql. How do i resolve the error and make it part of the string
DECLARE #columns NVARCHAR(MAX) = '', #sql NVARCHAR(MAX) = '';
SELECT
#columns = coalesce(#columns + ',', '') + quotename(Limit_Mins)
from
(
select DISTINCT
(L.Limit_Mins ) as 'Limit_Mins'
from
Limit L
)
AS lIMITS
SELECT #columns
SET
#sql = 'select * from (
SELECT
month (Sa.[Date]) AS 'Month_Name',
convert(varchar(10),
case
when
S.Limit_Mins = L.Limit_Mins
and S.Childcare_Flag = 1
then
S.Limit_Mins
else
0
end
) as 'Limit_Mins', sum(
case
when
S.Childcare_Flag = 1
and S.Limit_Mins = L.Limit_Mins
then
case
when
D.PID = Sa.PID
and D.Discount_Date = Sa.[Date]
then
D.Discount_Price
else
P.Retail_price
end
*Sa.Quantity
else
0
end
) as 'Amount'
FROM
Limit L
join
Store S
on L.Limit_Mins = S.Limit_Mins
join
Sale Sa
on S.Store_Number = Sa.Store_number
join
[Date] Dt
on Dt.[Date] = Sa.[Date]
join
Product P
on Sa.PID = P.PID
left outer join
Discount D
on Sa.PID = D.PID
and Sa.[Date] = D.Discount_Date
WHERE
Sa.[Date] >= DATEADD(year, - 1, DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1))
AND Sa.[Date] < DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1) -- DATEDIFF(MM,Sale.[Date] ,GETDATE())<=12
--and Sale.[Date] < DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
GROUP BY
month(Sa.[Date]) ,
case
when
S.Limit_Mins = L.Limit_Mins
and S.Childcare_Flag = 1
then
S.Limit_Mins
else
0
end
union all
SELECT
month (Sa.[Date]) AS 'Month_Name',
''No Childcare'' as 'Limit_Mins',
isnull(sum(
case
when
S.Childcare_Flag = 0
then
case
when
D.PID = Sa.PID
and D.Discount_Date = Sa.[Date]
then
D.Discount_Price
else
P.Retail_price
end
*Sa.Quantity
else
0
end
), 0) as 'Sales_Amount'
FROM
Store S
join
Sale Sa
on S.Store_Number = Sa.Store_number
join
[Date] Dt
on Dt.[Date] = Sa.[Date]
join
Product P
on Sa.PID = P.PID
left outer join
Discount D
on Sa.PID = D.PID
and Sa.[Date] = D.Discount_Date
WHERE
Sa.[Date] >= DATEADD(year, - 1, DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1))
AND Sa.[Date] < DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1) -- DATEDIFF(MM,Sale.[Date] ,GETDATE())<=12
--and Sale.[Date] < DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
GROUP BY
month(Sa.[Date])
)
A PIVOT(sum(Amount) for Limit_Mins in
(
'+#columns+
',[No Childcare]
)
)as PIVOTTable
order by
[Month]'
print #sql
Use brackets instead of quotes: month (Sa.[Date]) AS [Month_Name],
I tried the quotes earlier, but it was throwing an error invalid column which i later realized was happening because i renamed the alias and forgot to rename the same column order by , Thanks for the input

Query never finishes

So I have a query for a report that never finishes. I've allowed it to run for upwards of 20+ mins without completing. Here is the query:
DECLARE #start DATE, #end DATE
SET #start = '7-1-2019'
SET #end = '8-20-2019'
SELECT cg.*
,ba.std_StandardAcctNo AS bonus_acct
FROM [CustSalesTrend_Growth] cg
LEFT JOIN (
SELECT DISTINCT std_standardacctno
FROM [CustSalesTrend_Growth]
WHERE eleph_Period_Date BETWEEN #Start
AND #End
OR ideal_Period_Date BETWEEN #Start
AND #End
) ba ON ba.std_StandardAcctNo = cg.std_StandardAcctNo
AND cg.Period_Date >= #Start
AND cg.Period_Date <= #End
WHERE [Appearance_Count] <> 0
AND Period_gp <> 0
ORDER BY cg.std_StandardAcctNo
One of my first steps in diagnosing this is doing a simple select * on the view being referenced (CustSalesTrend_Growth) and it will finish running in about 30 seconds on average, pulling 12k records. Given this, I'm a little perplexed as to how the preceding query could add so much complexity to the execution, to the point that it never finishes. In my mind, the query above is relatively simple, so any ideas as to why this is happening?
EDIT: query for the view CustSalesTrend_Growth
CREATE VIEW [dbo].[CustSalesTrend_Growth]
AS
WITH basedata
AS (
SELECT DISTINCT a.order_num
,a.Period_Date
,a.year AS std_the_year
,a.Month AS std_the_month
,a.customer_alias AS std_StandardAcctNo
,b.SalesPerson_name
,isnull(ac.counter, 0) [Appearance_Count]
,isnull(b.[Year], 0) [The_Year]
,isnull(b.[Month], 0) [The_Month]
,isnull(b.Customer_Alias, 0) [CustomerName]
,sum(isnull(b.Gallons, 0)) [Gallon_Qty]
,sum(isnull(b.[Total Sale], 0)) [Total_Sale]
,sum(isnull(b.[Gross Profit], 0)) [Total_Gross_Profit]
FROM (
SELECT DISTINCT a.year
,a.month
,b.Customer_Alias
,convert(INTEGER, convert(VARCHAR(4), a.Year) + right('00' + convert(VARCHAR(2), a.month), 2)) AS order_num
,convert(DATE, convert(VARCHAR(2), a.Month) + '/01/' + convert(VARCHAR(4), a.Year)) AS Period_Date
FROM Complete_Sales_V2 a
JOIN (
SELECT DISTINCT Customer_Alias
FROM Complete_Sales_V2
) b ON 1 = 1
) a
JOIN PDI_Warehouse_2049_01.dbo.Appearance_Count ac ON a.Customer_Alias = ac.customer_alias
LEFT JOIN Complete_Sales_V2 b ON a.Customer_Alias = b.Customer_Alias
AND a.Month = b.Month
AND a.Year = b.Year
GROUP BY a.order_num
,a.Period_Date
,a.year
,a.Month
,a.Customer_Alias
,b.SalesPerson_Name
,ac.counter
,b.[Year]
,b.[Month]
,b.Customer_Alias
)
,saleslist
AS (
SELECT DISTINCT SalesPerson_Name
,Appearance_Count
,Period_Date
,std_the_month
,std_the_year
,std_StandardAcctNo
,isnull(sum(Total_Gross_Profit), 0) Period_GP
FROM basedata
GROUP BY SalesPerson_Name
,Appearance_Count
,Period_Date
,std_StandardAcctNo
,std_the_month
,std_the_year
)
,core_GP
AS (
SELECT DISTINCT a.Customer_Alias
,convert(DATE, convert(VARCHAR(2), a.month) + '/01/' + convert(VARCHAR(4), a.year)) AS Period_Date
,sum(a.[Gross Profit]) AS Period_GP
FROM Complete_Sales_V2 a
JOIN PDI_Warehouse_2049_01.dbo.appearance_count ac ON ac.customer_alias = a.Customer_Alias
GROUP BY counter
,convert(DATE, convert(VARCHAR(2), a.month) + '/01/' + convert(VARCHAR(4), a.year))
,a.Customer_Alias
)
,GroupedData
AS (
SELECT DISTINCT cgp.std_StandardAcctNo
,cgp.Period_Date
,sum(cgp.[Total_Gross_Profit]) AS Period_GP
,Appearance_Count
FROM basedata cgp
GROUP BY cgp.std_StandardAcctNo
,cgp.Period_Date
,Appearance_Count
)
,GP_Grouping
AS (
SELECT std_StandardAcctNo
,min(Period_Date) AS range_start
,max(Period_Date) AS range_end
,count(*) AS range_count
,GP_group
FROM (
SELECT std_StandardAcctNo
,Period_Date
,CASE
WHEN Period_GP = 0
THEN 0
ELSE 1
END AS GP_Group
,row_number() OVER (
PARTITION BY std_StandardAcctNo
,CASE
WHEN Period_GP = 0
THEN 0
ELSE 1
END ORDER BY Period_Date
) AS rn
,row_number() OVER (
PARTITION BY std_StandardAcctNo
,CASE
WHEN Period_GP = 0
THEN 0
ELSE 1
END ORDER BY Period_Date
) - row_number() OVER (
PARTITION BY std_StandardAcctNo ORDER BY Period_Date
) AS grp
,row_number() OVER (
PARTITION BY std_StandardAcctNo ORDER BY Period_Date
) AS grp2
FROM GroupedData
) a
GROUP BY std_StandardAcctNo
,grp
,GP_Group
)
,GP_Group2
AS (
SELECT gd.*
,max(gpg_prev.range_end) AS last_zero_group -- , gpg.range_count
FROM GroupedData gd
LEFT JOIN GP_Grouping gpg ON gd.std_StandardAcctNo = gpg.std_StandardAcctNo
AND gd.Period_Date BETWEEN gpg.range_start
AND gpg.range_end
LEFT JOIN (
SELECT *
FROM GP_Grouping
WHERE GP_Group = 0
AND range_count >= 12
) gpg_prev ON gpg_prev.std_StandardAcctNo = gd.std_StandardAcctNo
AND gpg.range_start > gpg_prev.range_end
GROUP BY gd.std_StandardAcctNo
,Period_Date
,Period_GP
,Appearance_Count
,gpg.range_count
)
,GP_Group3
AS (
SELECT gd.*
,Appearance_Cnt_Rel = CASE
WHEN gd.last_zero_group IS NULL
THEN Appearance_Count
ELSE ROW_NUMBER() OVER (
PARTITION BY gd.std_StandardAcctNo
,gd.last_zero_group ORDER BY gd.Period_Date
)
END
FROM GP_Group2 gd
)
,almost_done
AS (
SELECT DISTINCT bd.order_num
,bd.Period_Date
,bd.std_the_year
,bd.std_the_month
,bd.std_StandardAcctNo
,CASE
WHEN bd.[Appearance_Count] > 0
THEN bd.[Appearance_Count]
WHEN isnull(c.Appearance_Count, 0) > 0
THEN c.Appearance_Count + 1
WHEN isnull(d.Appearance_Count, 0) > 0
THEN d.Appearance_Count + 2
WHEN isnull(e.Appearance_Count, 0) > 0
THEN e.Appearance_Count + 3
ELSE 0
END AS Appearance_Count
,bd.[The_Year]
,bd.[The_Month]
,bd.[CustomerName]
,bd.[Gallon_Qty]
,bd.[Total_Sale]
,isnull(c.Appearance_Count, 0) AS Prev_Count
,isnull(d.Appearance_Count, 0) AS month2_Count
,isnull(e.Appearance_Count, 0) AS month3_Count
,CASE
WHEN bd.SalesPerson_Name IS NOT NULL
THEN bd.SalesPerson_Name
WHEN c.SalesPerson_Name IS NOT NULL
THEN c.SalesPerson_Name
WHEN d.SalesPerson_Name IS NOT NULL
THEN d.SalesPerson_Name
WHEN e.SalesPerson_Name IS NOT NULL
THEN e.SalesPerson_Name
ELSE 'NA'
END [SalesPerson]
,CASE
WHEN bd.[Appearance_Count] IS NULL
AND c.[Appearance_Count] IS NULL
AND d.[Appearance_Count] IS NULL
THEN e.Period_GP
ELSE 0
END [Lost_Gross_Profit]
,CASE
WHEN bd.Appearance_Count = 1
THEN bd.Total_Gross_Profit
ELSE 0
END AS 'New_Cust_GP'
,CASE
WHEN bd.Appearance_Count <= 12
THEN bd.Total_Gross_Profit
ELSE 0
END AS 'Young_Cust_GP'
,CASE
WHEN bd.Appearance_Count > 12
THEN bd.Total_Gross_Profit
ELSE 0
END AS 'Old_Cust_GP'
,ROW_NUMBER() OVER (
PARTITION BY bd.std_StandardAcctNo
,bd.std_The_Year
,bd.std_The_Month ORDER BY (bd.std_StandardAcctNo) DESC
) AS UNI_Period
,bd.Total_Gross_Profit AS SalesP_GP
,isnull(cg.Period_gp, 0) AS Period_gp
,CASE
WHEN isnull(b_prev.Period_gp, 0) > 0
THEN isnull(b_prev.Period_gp, 0)
WHEN isnull(d.Period_gp, 0) > 0
THEN isnull(d.Period_gp, 0)
WHEN isnull(e.Period_gp, 0) > 0
THEN isnull(e.Period_gp, 0)
ELSE 0
END AS Prev_Period_GP
,h.Mat_MoM_Shift
,CASE
WHEN isnull(b_prev.Period_gp, 0) > 0
THEN isnull(b_prev.Period_gp, 0)
WHEN isnull(d.Period_gp, 0) > 0
THEN isnull(d.Period_gp, 0)
WHEN isnull(e.Period_gp, 0) > 0
THEN isnull(e.Period_gp, 0)
ELSE 0
END * h.Mat_MoM_Shift AS Expected_GP
,isnull(c.Period_gp, 0) AS True_Prev_GP
,isnull(d.Period_gp, 0) AS True_2month_GP
,isnull(e.Period_gp, 0) AS True_3month_GP
,ideal_candidate = CASE
WHEN ((isnull(c.Period_gp, 0) + isnull(d.Period_gp, 0) + isnull(bd.Total_Gross_Profit, 0)) / 3 >= 800)
AND isnull(c.Period_gp, 0) >= 150
AND isnull(d.Period_gp, 0) >= 150
AND isnull(bd.Total_Gross_Profit, 0) >= 150
THEN 'Y'
ELSE 'N'
END
,eleph_candidate = CASE
WHEN ((isnull(c.Period_gp, 0) + isnull(d.Period_gp, 0) + isnull(bd.Total_Gross_Profit, 0)) / 3 >= 5000)
AND isnull(c.Period_gp, 0) >= 1000
AND isnull(d.Period_gp, 0) >= 1000
AND isnull(bd.Total_Gross_Profit, 0) >= 1000
THEN 'Y'
ELSE 'N
'
END
FROM basedata bd
LEFT JOIN core_GP b_prev ON bd.std_StandardAcctNo = b_prev.Customer_Alias
AND b_prev.Period_Date = dateadd(month, - 1, bd.Period_Date)
LEFT JOIN saleslist c ON c.std_StandardAcctNo = bd.std_StandardAcctNo
AND c.Period_Date = dateadd(month, - 1, bd.Period_Date)
AND CASE
WHEN bd.SalesPerson_Name IS NOT NULL
THEN bd.SalesPerson_Name
ELSE c.SalesPerson_Name
END = c.SalesPerson_Name
LEFT JOIN saleslist d ON d.std_StandardAcctNo = bd.std_StandardAcctNo
AND d.Period_Date = dateadd(month, - 2, bd.Period_Date)
AND CASE
WHEN bd.SalesPerson_Name IS NOT NULL
THEN bd.SalesPerson_Name
WHEN c.SalesPerson_Name IS NOT NULL
THEN c.SalesPerson_Name
ELSE d.SalesPerson_Name
END = d.SalesPerson_Name
LEFT JOIN saleslist e ON e.std_StandardAcctNo = bd.std_StandardAcctNo
AND e.Period_Date = dateadd(month, - 3, bd.Period_Date)
AND CASE
WHEN bd.SalesPerson_Name IS NOT NULL
THEN bd.SalesPerson_Name
WHEN c.SalesPerson_Name IS NOT NULL
THEN c.SalesPerson_Name
WHEN d.SalesPerson_Name IS NOT NULL
THEN d.SalesPerson_Name
ELSE e.SalesPerson_Name
END = e.SalesPerson_Name
LEFT JOIN RicoCustom.dbo.[Rico_Global_Monthly] h ON h.month = bd.std_the_month
LEFT JOIN core_GP cg ON bd.std_StandardAcctNo = cg.Customer_Alias
AND cg.Period_Date = bd.Period_Date
)
,get_ideal
AS (
SELECT DISTINCT min(ad.Period_Date) AS ideal_Period_Date
,ad.std_StandardAcctNo
,rc.last_zero_group
FROM almost_done ad
LEFT JOIN GP_Group3 rc ON rc.Period_Date = ad.Period_Date
AND rc.std_StandardAcctNo = ad.std_StandardAcctNo
AND rc.Period_GP = ad.Period_gp
WHERE ideal_candidate = 'Y'
AND (
rc.Appearance_Cnt_Rel BETWEEN 3
AND 6
)
GROUP BY ad.std_StandardAcctNo
,rc.last_zero_group
)
,get_elephant
AS (
SELECT DISTINCT min(ad.Period_Date) AS eleph_Period_Date
,ad.std_StandardAcctNo
,rc.last_zero_group
FROM almost_done ad
LEFT JOIN GP_Group3 rc ON rc.Period_Date = ad.Period_Date
AND rc.std_StandardAcctNo = ad.std_StandardAcctNo
AND rc.Period_GP = ad.Period_gp
WHERE eleph_candidate = 'Y'
AND (
rc.Appearance_Cnt_Rel BETWEEN 3
AND 36
)
GROUP BY ad.std_StandardAcctNo
,rc.last_zero_group
)
SELECT rc.Appearance_Cnt_Rel
,gi.ideal_Period_Date
,ge.eleph_Period_Date
,ad.*
FROM almost_done ad
LEFT JOIN GP_Group3 rc ON rc.Period_Date = ad.Period_Date
AND rc.std_StandardAcctNo = ad.std_StandardAcctNo
AND rc.Period_GP = ad.Period_gp
LEFT JOIN get_ideal gi ON ad.std_StandardAcctNo = gi.std_StandardAcctNo
AND ad.Period_Date = gi.ideal_Period_Date
LEFT JOIN get_elephant ge ON ad.std_StandardAcctNo = ge.std_StandardAcctNo
AND ad.Period_Date = ge.eleph_Period_Date
WHERE order_num > 201001
The indexing I have exists on the source table, Complete_Sales_V2. It is as follows:
index desc:
clustered, unique, primary key located on PRIMARY
index keys:
Customer_Alias, SalesPerson_Name, year, month, Invoice_Number
Since you say you can query the view I suggest selecting your view into a temp table prior to performing the query. This will simplify the query plan, allowing you to inspect it. And may hopefully speed it up.
I note in your original query you are filtering you main table against #Start and #End in the join condition. I don't think you want to do that. I think it should be in the where clause.
Also you can probably pre-filter the temp table so long as you can work out which records may be required (I couldn't because you compare to 3 different dates).
DECLARE #start DATE = '7-1-2019', #end DATE = '8-20-2019';
-- Best practice is to list the actual columns required
-- You may also be able to pre-filter here based on #start and #end
-- But as you compare them to 3 different columns in the query I don't know enough about your logic to know if this is possible or not
-- You can also add indexes to the temp table if they would speed things up
select *
into #cg
from [CustSalesTrend_Growth];
SELECT cg.*
, ba.std_StandardAcctNo AS bonus_acct
FROM #cg cg
LEFT JOIN (
SELECT DISTINCT std_standardacctno
FROM #cg
WHERE eleph_Period_Date BETWEEN #Start AND #End
OR ideal_Period_Date BETWEEN #Start AND #End
) ba ON ba.std_StandardAcctNo = cg.std_StandardAcctNo
WHERE [Appearance_Count] <> 0
AND Period_gp <> 0
AND cg.Period_Date >= #Start
AND cg.Period_Date <= #End
ORDER BY cg.std_StandardAcctNo;
drop table #cg;
Try this query that uses CTEs. I do not have the schema so some of my assumptions may not be correct. Please verify the query before you execute.
WITH t1 AS
(
SELECT *
FROM CustSalesTrend_Growth
WHERE Appearance_Count <> 0
AND Period_gp <> 0
AND Period_Date between #Start and #End
),
t2 AS
(
SELECT DISTINCT std_StandardAcctNo
FROM CustSalesTrend_Growth
WHERE eleph_Period_Date BETWEEN #Start AND #End
OR ideal_Period_Date BETWEEN #Start AND #End
)
select t1.*, t2.std_StandardAcctNo AS bonus_acct
FROM t1
LEFT JOIN t2 ON t2.std_StandardAcctNo = t1.std_StandardAcctNo
ORDER BY t2.std_StandardAcctNo

SQL Server n Times Fixed Pivot

So, business people have asked me to display the data in a particular way.
They need to display X amount of columns for a particular value and if the value is not there, then fill it with zero.
In other words, what I have:
And what I need:
I dont know if I should approach this with a pivot or a CTE and a loop... can you help me?
Using SQL Server 2008.
You can use ROW_NUMBER and conditional aggregation to do this pivoting
WITH cte
AS (SELECT RECORD_ID,
NUMBER,
Row_number() OVER(PARTITION BY RECORD_ID ORDER BY NUMBER ) AS RN
FROM yourtable)
SELECT RECORD_ID,
COALESCE(Max(CASE WHEN rn = 1 THEN NUMBER END),0) AS NUMBER01,
COALESCE(Max(CASE WHEN rn = 2 THEN NUMBER END),0) AS NUMBER02,
COALESCE(Max(CASE WHEN rn = 3 THEN NUMBER END),0) AS NUMBER03,
COALESCE(Max(CASE WHEN rn = 4 THEN NUMBER END),0) AS NUMBER04,
COALESCE(Max(CASE WHEN rn = 5 THEN NUMBER END),0) AS NUMBER05,
...
COALESCE(Max(CASE WHEN rn = 10 THEN NUMBER END),0) AS NUMBER10
FROM CTE
GROUP BY RECORD_ID
Dynamic approach
DECLARE #x INT = 10, -- Replace it with required of columns
#intr INT = 1,
#col_list VARCHAR(8000)='',
#sql VARCHAR(max)=''
SET #sql = ' WITH cte
AS (SELECT RECORD_ID,
NUMBER,
Row_number() OVER(PARTITION BY RECORD_ID ORDER BY NUMBER ) AS RN
FROM yourtable)
SELECT RECORD_ID, '
/*nothing to worry about the below while loop it is just to frame the string*/
WHILE #intr <= #x
BEGIN
SET #col_list += 'COALESCE(Max(CASE WHEN rn = ' + Cast(#intr AS VARCHAR(50)) + ' THEN NUMBER END),0) AS NUMBER' + Cast(#intr AS VARCHAR(50)) + ','
SET #intr += 1
END
SET #col_list = LEFT(#col_list, Len(#col_list) - 1)
SET #sql += #col_list + ' FROM CTE
GROUP BY RECORD_ID '
EXEC ( #sql )

How to display all the days of a month in SQL Server 2008?

I have written a query like
SELECT
Sum(a.in_total) as Totall,
DATEPART(dd, a.in_date_issued) as dateissued
FROM
dbo.IN_Invoices as a
WHERE
DATEPART(mm, a.in_date_issued) = 5
AND DATEPART(yyyy, a.in_date_issued)= 2015
AND a.sy_id='DPI'
AND EXISTS(SELECT DISTINCT cl_id as clid
FROM dbo.cloi_clientorderitems as c
WHERE c.masterorderid=a.masterorderid)
--AND c.cl_id NOT IN ('100001_DPO'))
GROUP BY
DATEPART(dd, a.in_date_issued)
ORDER BY dateissued ASC
This query will written the out put like
Total| day
100 | 1
0 | 3
150 | 10
-
-
200 | 31
Expected output
Total| day
100 | 1
150 | 2
0 | 3
600 | 4
-
-
200 | 31
Please help me in that query.
You can try something like this:
DECLARE #y INT;
DECLARE #m INT;
SET #y = 2015;
SET #m = 5;
WITH
m AS(SELECT 1 AS d UNION ALL SELECT d+1 FROM m WHERE d < datediff(d, DATEADD(mm, #m - 1, CAST(#y AS VARCHAR(8)) + '0101'), dateadd(m, 1, DATEADD(mm, #m - 1, CAST(#y AS VARCHAR(8)) + '0101'))))
SELECT isnull(Totall, 0) AS Totall, m.d AS dateissued
FROM m
LEFT JOIN(
SELECT SUM(a.in_total) AS Totall ,
DATEPART(dd, a.in_date_issued) AS dateissued
FROM dbo.IN_Invoices AS a
WHERE DATEPART(mm, a.in_date_issued) = #m
AND DATEPART(yyyy, a.in_date_issued) = #y
AND a.sy_id = 'DPI'
AND EXISTS ( SELECT DISTINCT
cl_id AS clid
FROM dbo.cloi_clientorderitems AS c
WHERE c.masterorderid = a.masterorderid )
--and c.cl_id not in ('100001_DPO'))
GROUP BY DATEPART(dd, a.in_date_issued)
)t ON m.d = t.dateissued
ORDER BY m.d ASC

How to make Query for that

I have a table structure from there i have to make a query in some different way
Table Structure
id unique identifier
code varchar(5) Not Null
Recording_date Datetime Not Null
Max_Temp numeric(5,2) Not Null
Min_Temp numeric(5,2) Not Null
We have some data as well in this table.We have data only for 2013 year and for first 3 months.
But the main thing is that i have to return's data in such a format like
Please help me to create a query for such a logic.
Thanks in advance.
Presuming you have one recording per day then
SELECT
DATEPART(m, Month_Start) + ' ' + DATEPART(yyyy, Month_Start)
, Max_Temp_Days
, CASE
WHEN Denominator = 0 THEN 0
ELSE (Max_Temp_Days / Denominator) * 100
END AS Percent_Max_Temp_Days
, Min_Temp_Days
, CASE
WHEN Denominator = 0 THEN 0
ELSE (Min_Temp_Days / Denominator) * 100
END AS Percent_Max_Temp_Days
FROM (
SELECT
DATEADD(MONTH, DATEDIFF(MONTH, 0, Recording_Date), 0) Month_Start
, Sum(CASE WHEN Max_Temp <= 0 THEN 1 END) Max_Temp_Days
, Sum(CASE WHEN Min_Temp <= 0 THEN 1 END) Min_Temp_Days
, COUNT(*) Denominator
FROM TemperatureRecordings
WHERE Recording_Date BETWEEN '2013-01-01' AND '2013-03-31'
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Recording_Date), 0)
) t
ORDER BY Month_Start
This works for all month data
DECLARE #maxTempratureTable table(monthName varchar(20), [No. of days Max<=0] int,[Percentage Max <=0] float)
INSERT INTO maxTempratureTable
SELECT RIGHT(CONVERT(VARCHAR, Recording_date, 106), 8) ,
COUNT(*) ,
COUNT(*) / DAY(DATEADD(mm,DATEDIFF(mm,-1,Recording_date),-1)) * 100
FROM tablename
WHERE Max_Temp <=0
GROUP BY RIGHT(CONVERT(VARCHAR, Recording_date, 106), 8)
DECLARE #minTempratureTable table(monthName varchar(20), [No. of days Min<=0] int,[Percentage Min<=0] float)
INSERT INTO #minTempratureTable
SELECT RIGHT(CONVERT(VARCHAR, Recording_date, 106), 8) ,
COUNT(*) ,
COUNT(*) / DAY(DATEADD(mm,DATEDIFF(mm,-1,Recording_date),-1)) * 100
FROM tablename
WHERE Min_Temp <=0
GROUP BY RIGHT(CONVERT(VARCHAR, Recording_date, 106), 8)
SELECT * FROM #minTempratureTable min
INNER JOIN #maxTempratureTable max
ON min.monthName = max.monthName
SELECT
MONTH(Recording_date),
SUM(CASE WHEN Max_Temp <= 0 THEN 1 ELSE 0 END),
SUM(CASE WHEN Max_Temp <= 0 THEN 1 ELSE 0 END) / COUNT(*),
SUM( CASE WHEN Min_Temp <= 0 THEN 1 ELSE 0 END ),
SUM( CASE WHEN Min_Temp <= 0 THEN 1 ELSE 0 END ) / COUNT(*)
FROM temperatures
GROUP BY MONTH(Recording_date)

Resources