Related
I have following table
ID
Name
StartDate
EndDate
1
Aa
2021-10-14
2021-12-22
2
Ab
2021-12-02
2022-10-05
The requirement is to add new columns in YYYYMM format consisting of all the months between min(StartDate) and max(EndDate), and assign values to the corresponding cells. The cell value should be 1 if the date lies between StartDate and EndDate in that row, and should be 0 if it does not fall within that date range.The final output should be like in the below table
ID
Name
StartDate
EndDate
202110
202111
202112
202201
202202
202203
202204
202205
202206
202207
1
Aa
2021-10-14
2021-12-22
1
1
1
0
0
0
0
0
0
0
2
Ab
2021-12-02
2022-07-05
0
0
1
1
1
1
1
1
1
1
For the 1st row, since the startdate=2021-10-14 & EndDate=2021-12-22, corresponding new columns should be 202110,202111 & 202112; and corresponding cell values are 1 for these columns while the other cells are 0. Same logic should be applied to other rows as well.
I could not figure out the logic to derive new tables with new columns and corresponding cell values.
How about this approach using dynamic SQL:
CREATE TABLE Data ( ID INT, Name VARCHAR(100), StartDate DATE, EndDate DATE )
INSERT Data
VALUES
('1', 'Aa', '2021-10-14', '2021-12-22'),
('2', 'Ab', '2021-12-02', '2022-10-05')
-- Extract overall date range
DECLARE #MinStartDate DATE, #MaxEndDate AS DATE
SELECT #MinStartDate = MIN(StartDate), #MaxEndDate = MAX(EndDate)
FROM Data
-- Convert to months (DATETRUNC() may be used instead with SQL Server 2022 and later)
DECLARE #StartMonth DATE = DATEADD(day, 1 - DAY(#MinStartDate), #MinStartDate)
DECLARE #EndMonth DATE = DATEADD(day, 1 - DAY(#MaxEndDate), #MaxEndDate)
-- Generate calendar of months within range
DECLARE #Months TABLE ( Month DATE)
;WITH Months AS (
SELECT #StartMonth AS Month
UNION ALL
SELECT DATEADD(month, 1, M.Month)
FROM Months M
WHERE M.Month < #EndMonth
)
INSERT #Months
SELECT M.Month
FROM Months M
-- Define SQL Templates
DECLARE #SqlTemplate VARCHAR(MAX) = '
SELECT ID, Name, StartDate, EndDate
<ColumnSql>
FROM Data D
ORDER BY D.Name
'
DECLARE #ColumnTemplate VARCHAR(MAX) = '
, CASE WHEN D.StartDate <= <MonthEnd> AND <MonthStart> <= D.EndDate THEN 1 ELSE 0 END AS <ColumnName>'
-- Build month-specific column select items from template
DECLARE #ColumnSql VARCHAR(MAX) = (
SELECT STRING_AGG(C.ColumnSql, '') WITHIN GROUP(ORDER BY M.Month)
FROM #Months M
CROSS APPLY (
SELECT
CONVERT(CHAR(6), M.Month, 112) AS ColumnName,
M.Month AS MonthStart,
EOMONTH(M.Month) AS MonthEnd
) MD
CROSS APPLY (
SELECT REPLACE(REPLACE(REPLACE(
#ColumnTemplate
, '<ColumnName>', QUOTENAME(MD.ColumnName))
, '<MonthStart>', QUOTENAME(CONVERT(CHAR(8), MD.MonthStart, 112), ''''))
, '<MonthEnd>', QUOTENAME(CONVERT(CHAR(8), MD.MonthEnd, 112), ''''))
AS ColumnSql
) C
)
--SELECT #ColumnSql
-- Build final SQL
DECLARE #Sql VARCHAR(MAX) = REPLACE(#SqlTemplate, '<ColumnSql>', #ColumnSql)
SELECT #Sql
-- Deliver
EXEC (#Sql)
Generated SQL:
SELECT ID, Name, StartDate, EndDate
, CASE WHEN D.StartDate <= '20211031' AND D.EndDate >= '20211001' THEN 1 ELSE 0 END AS [202110]
, CASE WHEN D.StartDate <= '20211130' AND D.EndDate >= '20211101' THEN 1 ELSE 0 END AS [202111]
, CASE WHEN D.StartDate <= '20211231' AND D.EndDate >= '20211201' THEN 1 ELSE 0 END AS [202112]
, CASE WHEN D.StartDate <= '20220131' AND D.EndDate >= '20220101' THEN 1 ELSE 0 END AS [202201]
, CASE WHEN D.StartDate <= '20220228' AND D.EndDate >= '20220201' THEN 1 ELSE 0 END AS [202202]
, CASE WHEN D.StartDate <= '20220331' AND D.EndDate >= '20220301' THEN 1 ELSE 0 END AS [202203]
, CASE WHEN D.StartDate <= '20220430' AND D.EndDate >= '20220401' THEN 1 ELSE 0 END AS [202204]
, CASE WHEN D.StartDate <= '20220531' AND D.EndDate >= '20220501' THEN 1 ELSE 0 END AS [202205]
, CASE WHEN D.StartDate <= '20220630' AND D.EndDate >= '20220601' THEN 1 ELSE 0 END AS [202206]
, CASE WHEN D.StartDate <= '20220731' AND D.EndDate >= '20220701' THEN 1 ELSE 0 END AS [202207]
, CASE WHEN D.StartDate <= '20220831' AND D.EndDate >= '20220801' THEN 1 ELSE 0 END AS [202208]
, CASE WHEN D.StartDate <= '20220930' AND D.EndDate >= '20220901' THEN 1 ELSE 0 END AS [202209]
, CASE WHEN D.StartDate <= '20221031' AND D.EndDate >= '20221001' THEN 1 ELSE 0 END AS [202210]
FROM Data D
ORDER BY D.Name
Results:
ID
Name
StartDate
EndDate
202110
202111
202112
202201
202202
202203
202204
202205
202206
202207
202208
202209
202210
1
Aa
2021-10-14
2021-12-22
1
1
1
0
0
0
0
0
0
0
0
0
0
2
Ab
2021-12-02
2022-10-05
0
0
1
1
1
1
1
1
1
1
1
1
1
See this db<>fiddle.
The above uses a standard test for date range overlap of "start1 <= end2 AND start2 <= end1", which assumes all dates are inclusive.
I am trying to run 3 different select query on 1 table where i return the count of created, done, pending tasks based on created_date and modified_date
where i can differentiate the done from pending in modified_date based on the field status
when i run each query separately it return correct answer.
But what i want is to combine these 3 queries in one table as below:
+---------------------- +------------------+---------------------+
| Total_created_files | Total_done_files | Total_pending_files |
+-----------------------+------------------+---------------------+
| 14 | 40 | 9 |
+-----------------------+------------------+---------------------+
code:
select
count([create_date]) as Total_created_files
FROM [TEC_APP].[dbo].[case_to_do]
where [create_date] >='2022-05-01 00:00:00.000'
AND
CAST([create_date] AS date) <= CAST(GETDATE() AS date)
select
count([modified_date]) as Total_done_files
FROM [TEC_APP].[dbo].[case_to_do]
where [modified_date] >='2022-05-01 00:00:00.000'
AND
CAST([modified_date] AS date) <= CAST(GETDATE() AS date)
AND
status = 'DONE'
select
count([modified_date]) as Total_pending_files
FROM [TEC_APP].[dbo].[case_to_do]
where [modified_date] >='2022-05-01 00:00:00.000'
AND
CAST([modified_date] AS date) <= CAST(GETDATE() AS date)
AND
status = 'Pending'
Use conditional aggregation to COUNT as needed. I make a couple of assumptions here, but this should be what you are after:
USE TEC_APP;
GO
SELECT COUNT(CASE WHEN [create_date] < DATEADD(DAY,1,CONVERT(date,GETDATE())) THEN 1 END) AS Total_created_files,
COUNT(CASE WHEN [modified_date] >= '20220501' AND [modified_date] < DATEADD(DAY,1,CONVERT(date,GETDATE())) AND Status = 'DONE' THEN 1 END) AS Total_done_files,
COUNT(CASE WHEN [modified_date] >= '20220501' AND [modified_date] < DATEADD(DAY,1,CONVERT(date,GETDATE())) AND Status = 'Pending' THEN 1 END) AS Total_pending_files
FROM [dbo].[case_to_do]
WHERE create_date >= '20220501'; --Presumably something can't be modified before it's created.
Use conditional aggregation with case expression:
SELECT SUM(case when <First Condition here> then 1 else 0 end) as Total_created_files,
SUM(case when <Second Condition here> then 1 else 0 end) as Total_done_files,
SUM(case when <Third Condition here> then 1 else 0 end) as Total_pending_files
FROM [TEC_APP].[dbo].[case_to_do]
I have the below code. I am comparing counts from today's date to yesterday's date unless date falls on Monday then I want to use Friday's count.
select
cast(getdate() as date)run_dt,
'dx' as db,
'dbo' as [schema],
'tb_cust' as [table],
'completed status' as check_type,
a.curr_cnt,
a.prev_cnt,
abs(cast((a.prev_cnt - a.curr_cnt) / cast(a.curr_cnt as decimal(10,2)) as decimal(5,2))*100) as cal_prcnt_dff,
case
when abs(cast((a.prev_cnt - a.curr_cnt) / cast(a.curr_cnt as decimal(10,2)) * 100 as int) ) >= 100
then 'Y'
else 'N'
end email_trigger,
concat('count on',' ', #curr_dt,' ','[',datename(dw,#curr_dt),']',' ' ,'increased/decreased by 100% from',' ',#prev_dt,' ','[',datename(dw,#prev_dt),']') as 'comment'
from (select
sum(
case
when a.custstatus = 'completed'
and a.custdate = cast(getdate() -1 as date)
then 1
else 0
end) curr_cnt,
sum(
case
when a.custstatus = 'completed'
and a.custtdate = cast(getdate() -2 as date)
--and cast(getdate() as date) in ()
--and datepart(dw,getdate()) in (3,4,5,6)
--or
then 1
else 0
end) prev_cnt,
a.custstatus
from cte_apt a
where 1=1
and a.custstatus = 'completed'
group by
a.custstatus)a
How can I get prev_cnt to count Friday when the day lands on a Monday?
sum(
case
when a.custstatus = 'completed'
and a.custtdate = cast(getdate() -2 as date)
--and cast(getdate() as date) in ()
--and datepart(dw,getdate()) in (3,4,5,6)
--or
then 1
else 0
end) prev_cnt,
How should I rewrite below query to get desirable outcome? The last SUM gives me trouble.
SELECT ProducerCode,ProducerLocationID,
MAX(Producer) as Producer, -- using MAX() to combine same ProdCode and ProdLocation BUT diff ProdNames
SUM(premium) as NetWrittenPremium,
SUM(CASE WHEN PolicyType = 'New Business' THEN Premium ELSE 0 END) as WPNewBusiness,
SUM(CASE WHEN PolicyType = 'Renewal' THEN Premium ELSE 0 END) as WPRenewal,
SUM(CASE WHEN PolicyType = 'Rewrite' THEN Premium ELSE 0 END) as WPRewrite,
SUM(CASE WHEN PolicyType = 'New Business' AND Status = 'Bound' THEN 1 ELSE 0 END) as BindsNewBusiness,
SUM(CASE WHEN PolicyType = 'Renewal' AND Status = 'Bound' THEN 1 ELSE 0 END) as BindsRenewals,
SUM(CASE WHEN PolicyType = 'Rewrite' AND Status = 'Bound' THEN 1 ELSE 0 END) as BindsRewrite,
SUM(CASE WHEN PolicyType = 'New Business' AND Status = 'Bound' THEN 1 ELSE 0 END) + SUM(CASE WHEN PolicyType = 'Renewal' AND Status = 'Bound' THEN 1 ELSE 0 END) + SUM(CASE WHEN PolicyType = 'Rewrite' AND Status = 'Bound' THEN 1 ELSE 0 END) as PolicyCount,
COUNT (distinct ControlNo) as Submissions,
SUM(CASE WHEN QuotedPremium IS NOT NULL AND Status <> 'Quoted' THEN 1 ELSE 0 END ) as Rated,
SUM(CASE WHEN QuotedPremium IS NOT NULL AND Status = 'Quoted' THEN 1 ELSE 0 END) as Quoted,
--This is where it gets tricky---
---------------------------------------------------------------------------
SUM( CASE WHEN EXISTS (SELECT *
FROM tblQuoteStatusChangeLog
WHERE [dbo].[tblClearanceDataForMetricReports].ControlNo = tblQuoteStatusChangeLog.ControlNo
AND tblQuoteStatusChangeLog.NewQuoteStatusID IN (2,25,202)
) THEN 1 ELSE 0 END) as Quotes
----------------------------------------------------------------------------
FROM [dbo].[tblClearanceDataForMetricReports]
WHERE CAST(EffectiveDate AS DATE) >= DateAdd(yy, -1, DATEADD(d, 1, EOMONTH(GETDATE()))) AND CAST(EffectiveDate AS DATE) <= EOMONTH(GETDATE())
AND CompanyLocationGUID = '54A8FCCD-C7FE-4642-9C22-3A25207CDAEE'
AND LineGUID = '43280452-42E9-4D4C-9B72-C51DCF77BCD0'
GROUP BY ProducerCode,
ProducerLocationID
I tried to make it as a derived table, but also no success.
Select your data, then aggregate it:
SELECT ProducerCode,ProducerLocationID,
MAX(Producer) as Producer, -- using MAX() to combine same ProdCode and ProdLocation BUT diff ProdNames
SUM(premium) as NetWrittenPremium,
SUM(CASE WHEN PolicyType = 'New Business' THEN Premium ELSE 0 END) as WPNewBusiness,
SUM(CASE WHEN PolicyType = 'Renewal' THEN Premium ELSE 0 END) as WPRenewal,
SUM(CASE WHEN PolicyType = 'Rewrite' THEN Premium ELSE 0 END) as WPRewrite,
SUM(CASE WHEN PolicyType = 'New Business' AND Status = 'Bound' THEN 1 ELSE 0 END) as BindsNewBusiness,
SUM(CASE WHEN PolicyType = 'Renewal' AND Status = 'Bound' THEN 1 ELSE 0 END) as BindsRenewals,
SUM(CASE WHEN PolicyType = 'Rewrite' AND Status = 'Bound' THEN 1 ELSE 0 END) as BindsRewrite,
SUM(CASE WHEN PolicyType = 'New Business' AND Status = 'Bound' THEN 1 ELSE 0 END) + SUM(CASE WHEN PolicyType = 'Renewal' AND Status = 'Bound' THEN 1 ELSE 0 END) + SUM(CASE WHEN PolicyType = 'Rewrite' AND Status = 'Bound' THEN 1 ELSE 0 END) as PolicyCount,
COUNT (distinct ControlNo) as Submissions,
SUM(CASE WHEN QuotedPremium IS NOT NULL AND Status <> 'Quoted' THEN 1 ELSE 0 END ) as Rated,
SUM(CASE WHEN QuotedPremium IS NOT NULL AND Status = 'Quoted' THEN 1 ELSE 0 END) as Quoted,
SUM(Quotes) as Quotes
FROM (
SELECT ProducerCode,
ProducerLocationID,
Producer,
premium,
PolicyType,
ControlNo,
QuotedPremium,
STATUS,
CASE
WHEN EXISTS (
SELECT *
FROM tblQuoteStatusChangeLog
WHERE [dbo].[tblClearanceDataForMetricReports].ControlNo = tblQuoteStatusChangeLog.ControlNo
AND tblQuoteStatusChangeLog.NewQuoteStatusID IN (2, 25,202)
)
THEN 1
ELSE 0
END AS Quotes
FROM [dbo].[tblClearanceDataForMetricReports]
WHERE CAST(EffectiveDate AS DATE) >= DateAdd(yy, - 1, DATEADD(d, 1, EOMONTH(GETDATE())))
AND CAST(EffectiveDate AS DATE) <= EOMONTH(GETDATE())
AND CompanyLocationGUID = '54A8FCCD-C7FE-4642-9C22-3A25207CDAEE'
AND LineGUID = '43280452-42E9-4D4C-9B72-C51DCF77BCD0'
) sub
GROUP BY ProducerCode,
ProducerLocationID
Used subquery:
SELECT ProducerCode,ProducerLocationID,
MAX(Producer) as Producer, -- using MAX() to combine same ProdCode and ProdLocation BUT diff ProdNames
SUM(premium) as NetWrittenPremium,
SUM(CASE WHEN PolicyType = 'New Business' THEN Premium ELSE 0 END) as WPNewBusiness,
SUM(CASE WHEN PolicyType = 'Renewal' THEN Premium ELSE 0 END) as WPRenewal,
SUM(CASE WHEN PolicyType = 'Rewrite' THEN Premium ELSE 0 END) as WPRewrite,
SUM(CASE WHEN PolicyType = 'New Business' AND Status = 'Bound' THEN 1 ELSE 0 END) as BindsNewBusiness,
SUM(CASE WHEN PolicyType = 'Renewal' AND Status = 'Bound' THEN 1 ELSE 0 END) as BindsRenewals,
SUM(CASE WHEN PolicyType = 'Rewrite' AND Status = 'Bound' THEN 1 ELSE 0 END) as BindsRewrite,
SUM(CASE WHEN PolicyType = 'New Business' AND Status = 'Bound' THEN 1 ELSE 0 END) + SUM(CASE WHEN PolicyType = 'Renewal' AND Status = 'Bound' THEN 1 ELSE 0 END) + SUM(CASE WHEN PolicyType = 'Rewrite' AND Status = 'Bound' THEN 1 ELSE 0 END) as PolicyCount,
COUNT (distinct ControlNo) as Submissions,
SUM(CASE WHEN QuotedPremium IS NOT NULL THEN 1 ELSE 0 END ) as Rated,
--This is subquery--------------
(
SELECT COUNT( DISTINCT c.ControlNo) FROM [dbo].[tblClearanceDataForMetricReports] c INNER JOIN tblQuoteStatusChangeLog q ON c.ControlNo = q.ControlNo
AND q.NewQuoteStatusID IN (2,25,202)
WHERE CAST(EffectiveDate AS DATE) >= DateAdd(yy, -1, DATEADD(d, 1, EOMONTH(GETDATE()))) AND CAST(EffectiveDate AS DATE) <= EOMONTH(GETDATE())
AND CompanyLocationGUID = '54A8FCCD-C7FE-4642-9C22-3A25207CDAEE'
AND LineGUID = '43280452-42E9-4D4C-9B72-C51DCF77BCD0'
and c.ProducerCode = [dbo].[tblClearanceDataForMetricReports].ProducerCode
and c.ProducerLocationID = [dbo].[tblClearanceDataForMetricReports].ProducerLocationID
) as Quoted,
SUM(CASE WHEN Status = 'Declined' THEN 1 ELSE 0 END ) as Declined
FROM [dbo].[tblClearanceDataForMetricReports]
WHERE CAST(EffectiveDate AS DATE) >= DateAdd(yy, -1, DATEADD(d, 1, EOMONTH(GETDATE()))) AND CAST(EffectiveDate AS DATE) <= EOMONTH(GETDATE())
AND CompanyLocationGUID = '54A8FCCD-C7FE-4642-9C22-3A25207CDAEE'
AND LineGUID = '43280452-42E9-4D4C-9B72-C51DCF77BCD0'
GROUP BY ProducerCode,
ProducerLocationID
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.