Converting SQL Server UNPIVOT to TERADATA - sql-server

I am trying to convert the following code from SQL Server to Teradata using UNPIVOT logic:
insert into
IPData
select
1,
ProductCode || '|' ||
LocationCode || '|' ||
TimeCode || '|' ||
MeasureCode || '|' ||
cast(MeasureVal as varchar(12))
from
(
select
p.SubsectionCode ProductCode,
td_ss.LocationCode,
td_ss.TimeCode,
sum(
case
when td_ss.Life = 'C'
and td_ss.Seasonality = 'AW' then td_ss.DepotStockRetail
else 0
end) StkDep_AW_Act,
sum(
case
when td_ss.Life = 'C'
and td_ss.Seasonality = 'C' then td_ss.DepotStockRetail
else 0
end) StkDep_Cnt_Act,
sum(
case
when td_ss.Life = 'C'
and td_ss.Seasonality = 'SS' then td_ss.DepotStockRetail
else 0
end) StkDep_SS_Act,
sum(
case td_ss.Life
when 'T' then td_ss.DepotStockRetail
else 0
end) StkDep_Trm_Act,
sum(td_ss.DepotStockRetail) StkDep_Tot_Act
from
Stock td_ss
inner join
Product p
on td_ss.Kimball = p.CurrentKimball
and td_ss.SectArea = p.SectArea
and td_ss.SeasonID = p.SeasonID
group by
p.SubsectionCode,
td_ss.LocationCode,
td_ss.TimeCode)x
UNPIVOT
(MeasureVal for MeasureCode in
(StkDep_AW_Act, StkDep_Cnt_Act, StkDep_SS_Act, StkDep_Trm_Act, StkDep_Tot_Act)) as unpvt
where
MeasureVal <> 0;
I am struggling with the part of UNPIVOT. As of now I have no data in any of the tables , so any help regarding UNPIVOT is highly appreciated.

Teradata supports UNPIVOT in TD16, but the syntax it's closer to Oracle than to SQL Server.
Before there's a TD_UNPIVOT table operator, this should be the correct translation:
INSERT INTO
IPData
SELECT * FROM TD_UNPIVOT(
ON(
SELECT
1,
ProductCode || '|' ||
LocationCode || '|' ||
TimeCode || '|' ||
MeasureCode || '|' ||
Cast(MeasureVal AS VARCHAR(12))
FROM
(
SELECT
p.SubsectionCode ProductCode,
td_ss.LocationCode,
td_ss.TimeCode,
Sum(
CASE
WHEN td_ss.Life = 'C'
AND td_ss.Seasonality = 'AW' THEN td_ss.DepotStockRetail
ELSE 0
end) StkDep_AW_Act,
Sum(
CASE
WHEN td_ss.Life = 'C'
AND td_ss.Seasonality = 'C' THEN td_ss.DepotStockRetail
ELSE 0
end) StkDep_Cnt_Act,
Sum(
CASE
WHEN td_ss.Life = 'C'
AND td_ss.Seasonality = 'SS' THEN td_ss.DepotStockRetail
ELSE 0
end) StkDep_SS_Act,
Sum(
CASE td_ss.Life
WHEN 'T' THEN td_ss.DepotStockRetail
ELSE 0
end) StkDep_Trm_Act,
Sum(td_ss.DepotStockRetail) StkDep_Tot_Act
FROM
Stock td_ss
INNER JOIN
Product p
ON td_ss.Kimball = p.CurrentKimball
AND td_ss.SectArea = p.SectArea
AND td_ss.SeasonID = p.SeasonID
GROUP BY
p.SubsectionCode,
td_ss.LocationCode,
td_ss.TimeCode)x
) AS dt
USING
VALUE_COLUMNS('MeasureVal')
UNPIVOT_COLUMN('Measures')
COLUMN_LIST('StkDep_AW_Act', 'StkDep_Cnt_Act', 'StkDep_SS_Act', 'StkDep_Trm_Act', 'StkDep_Tot_Act')
) AS unpvt
WHERE
MeasureVal <> 0;

insert into IPData
select
1,
ProductCode || '|' ||
LocationCode || '|' ||
TimeCode || '|' ||
MeasureCode || '|' ||
cast(MeasureVal as varchar(12))
from
(Select
p.SubsectionCode ProductCode,
td_ss.LocationCode,
td_ss.TimeCode,
sum(case
when td_ss.Life = 'C' and td_ss.Seasonality = 'AW' then td_ss.DepotStockRetail
else 0
end) MeasureVal,'StkDep_AW_Act' AS MeasureCode
FROM Stock td_ss
inner join
Product p
on td_ss.Kimball = p.CurrentKimball
and td_ss.SectArea = p.SectArea
and td_ss.SeasonID = p.SeasonID
group by
p.SubsectionCode,
td_ss.LocationCode,
td_ss.TimeCode
having
MeasureVal <> 0
UNION ALL
Select
p.SubsectionCode ProductCode,
td_ss.LocationCode,
td_ss.TimeCode,
sum(case
when td_ss.Life = 'C' and td_ss.Seasonality = 'C' then td_ss.DepotStockRetail
else 0
end) MeasureVal, 'StkDep_Cnt_Act' AS MeasureCode
FROM Stock td_ss
inner join
Product p
on td_ss.Kimball = p.CurrentKimball
and td_ss.SectArea = p.SectArea
and td_ss.SeasonID = p.SeasonID
group by
p.SubsectionCode,
td_ss.LocationCode,
td_ss.TimeCode
having
MeasureVal <> 0
UNION ALL
Select
p.SubsectionCode ProductCode,
td_ss.LocationCode,
td_ss.TimeCode,
sum(case
when td_ss.Life = 'C' and td_ss.Seasonality = 'SS' then td_ss.DepotStockRetail
else 0
end) MeasureVal, 'StkDep_SS_Act' AS MeasureCode
FROM Stock td_ss
inner join
Product p
on td_ss.Kimball = p.CurrentKimball
and td_ss.SectArea = p.SectArea
and td_ss.SeasonID = p.SeasonID
group by
p.SubsectionCode,
td_ss.LocationCode,
td_ss.TimeCode
having
MeasureVal <> 0
UNION ALL
Select
p.SubsectionCode ProductCode,
td_ss.LocationCode,
td_ss.TimeCode,
sum(case td_ss.Life
when 'T' then td_ss.DepotStockRetail
else 0
end) MeasureVal, 'StkDep_Trm_Act' AS MeasureCode
FROM Stock td_ss
inner join
Product p
on td_ss.Kimball = p.CurrentKimball
and td_ss.SectArea = p.SectArea
and td_ss.SeasonID = p.SeasonID
group by
p.SubsectionCode,
td_ss.LocationCode,
td_ss.TimeCode
having
MeasureVal <> 0
UNION ALL
Select
p.SubsectionCode ProductCode,
td_ss.LocationCode,
td_ss.TimeCode,
sum(td_ss.DepotStockRetail) MeasureVal, 'StkDep_Tot_Act' AS MeasureCode
FROM Stock td_ss
inner join
Product p
on td_ss.Kimball = p.CurrentKimball
and td_ss.SectArea = p.SectArea
and td_ss.SeasonID = p.SeasonID
group by
p.SubsectionCode,
td_ss.LocationCode,
td_ss.TimeCode
having
MeasureVal <> 0
)x;

Related

SQL Server - Query with MAX(CASE ..) and GROUP BY runs too long

I added to my query max() and group by to exclude duplicates and now it's running very long, 56 minutes.
But before adding max() and group by it was running 7-8 min. It's ok, I'm using aggregate view in join and it takes time.
Without max() and group by I had duplicates of customers who opted-in and not opted-in. Where I wanted just to put value "1" if I see that customer has OptIn as "1".
Here is my code:
WITH
cteURC AS (
SELECT
distinct scvid
,MAX(CASE WHEN who = 'urc' AND OptIn = '1' THEN 1 ELSE 0 END) AS URC_OptIn
FROM
scv.OptIn
where who = 'urc'
),
cteSponsor AS (
SELECT
distinct scvid
,MAX(CASE WHEN who = 'sponsor/3rd party' AND OptIn = '1' THEN 1 ELSE 0 END) AS Partner_OptIn
FROM
scv.OptIn
where who = 'sponsor/3rd party'
GROUP BY scvid
),
cteLeinster AS (
SELECT
distinct scvid
,MAX(CASE WHEN who = 'leinster rugby' AND OptIn = '1' THEN 1 ELSE 0 END) AS Leinster_OptIn
FROM
scv.OptIn
where who = 'leinster rugby'
)
SELECT distinct(c.[ScvId])
,Title
,FirstName
,LastName
,EmailAddress
,DateOfBirth
,Address1
,City
,Telephone
,Gender
,URC_OptIn
,Partner_OptIn
,Leinster_OptIn
,MAX(CASE WHEN c.ScvId = T.ScvId AND ProductId = '2019' THEN 1 ELSE 0 END) AS FinalTicketPurchaser_2019
,MAX(CASE WHEN c.ScvId = T.ScvId AND ProductId = '2018' THEN 1 ELSE 0 END) AS FinalTicketPurchaser_2018
FROM scv.vwCustomer c
LEFT JOIN cteURC U ON c.scvid = U.scvid
LEFT JOIN cteSponsor S ON c.ScvId = S.ScvId
LEFT JOIN cteLeinster L on c.ScvId = L.ScvId
LEFT JOIN vwAggTransaction T ON c.ScvId = T.ScvId
group by c.[ScvId]
Title,
FirstName,
LastName,
EmailAddress,
DateOfBirth,
Address1,
City,
Telephone,
Gender,
URC_OptIn,
Partner_OptIn,
Leinster_OptIn,
order by c.scvid
How can I change query to make it run quicker?
Update
I became brave and re-wrote query. I was hesitating as my friend wrote the ctes and I thought that they are necessary.
This version works well and fast. Thank you everyone. I really appreciate your input!
SELECT (c.[ScvId])
,Title
,FirstName
,LastName
,EmailAddress
,DateOfBirth
,Address1
,City
,Telephone
,Gender
,MAX(CASE WHEN who = 'urc' AND OptIn = '1' THEN 1 ELSE 0 END) AS URC_OptIn
,MAX(CASE WHEN who = 'sponsor/3rd party' AND OptIn = '1' THEN 1 ELSE 0 END) AS Partner_OptIn
,MAX(CASE WHEN who = 'leinster rugby' AND OptIn = '1' THEN 1 ELSE 0 END) AS Leinster_OptIn
,MAX(CASE WHEN who = 'connacht rugby' AND OptIn = '1' THEN 1 ELSE 0 END) AS Connacht_OptIn
,MAX(CASE WHEN c.ScvId = T.ScvId AND ProductId = '2019' THEN 1 ELSE 0 END) AS FinalTicketPurchaser_2019
,MAX(CASE WHEN c.ScvId = T.ScvId AND ProductId = '2018' THEN 1 ELSE 0 END) AS FinalTicketPurchaser_2018
FROM vwCustomer c
LEFT JOIN OptIn o ON c.scvid = o.scvid
LEFT JOIN vwAggTransaction T ON c.ScvId = T.ScvId
group by c.[ScvId]
,Title
,FirstName
,LastName
,EmailAddress
,DateOfBirth
,Address1
,City
,Telephone
,Gender
order by c.scvid
I'm taking a stab at it without more information. I converted the CTE into OUTER APPLY. You might need to tweak it a bit for the cases when OptIn=0. Give it a try and see if the performance is any better.
SELECT distinct c.[ScvId]
,Title
,FirstName
,LastName
,EmailAddress
,DateOfBirth
,Address1
,City
,Telephone
,Gender
,URC_OptIn
,Partner_OptIn
,Leinster_OptIn
,MAX(CASE WHEN c.ScvId = T.ScvId AND ProductId = '2019' THEN 1 ELSE 0 END) AS FinalTicketPurchaser_2019
,MAX(CASE WHEN c.ScvId = T.ScvId AND ProductId = '2018' THEN 1 ELSE 0 END) AS FinalTicketPurchaser_2018
FROM scv.vwCustomer c
OUTER APPLY (
SELECT TOP 1 OptIn AS URC_OptIn
FROM scv.OptIn oiu
WHERE oiu.scvid = c.Scvid AND oiu.OptIn = '1' AND oiu.who = 'urc'
) AS U
OUTER APPLY (
SELECT TOP 1 OptIn AS Partner_OptIn
FROM scv.OptIn ois
WHERE ois.scvid = c.Scvid AND ois.OptIn = '1' AND ois.who = 'sponsor/3rd party'
) AS S
OUTER APPLY (
SELECT TOP 1 OptIn AS Leinster_OptIn
FROM scv.OptIn oil
WHERE oil.scvid = c.Scvid AND oil.OptIn = '1' AND oil.who = 'leinster rugby'
) AS L
LEFT JOIN vwAggTransaction T ON c.ScvId = T.ScvId
GROUP BY c.[ScvId]
Title,
FirstName,
LastName,
EmailAddress,
DateOfBirth,
Address1,
City,
Telephone,
Gender,
URC_OptIn,
Partner_OptIn,
Leinster_OptIn,
ORDER BY c.scvid

SQL Server : combine query result to one row

I want to format the query like this. is it possible?
With conditional aggregation:
SELECT
MAX(CASE WHEN CHECKTYPE = 'I' AND TIMETYPE = 'AM' THEN FORMAT(CHECKTIME, N'HH:mm') END) [AM-IN],
MAX(CASE WHEN CHECKTYPE = 'O' AND TIMETYPE = 'AM' THEN FORMAT(CHECKTIME, N'HH:mm') END) [AM-OUT],
MAX(CASE WHEN CHECKTYPE = 'I' AND TIMETYPE = 'PM' THEN FORMAT(CHECKTIME, N'HH:mm') END) [PM-IN],
MAX(CASE WHEN CHECKTYPE = 'O' AND TIMETYPE = 'PM' THEN FORMAT(CHECKTIME, N'HH:mm') END) [PM-OUT]
FROM [dbo].[CHECKINOUT]
WHERE [USERID] = N'21477' AND [CHECKTIME] BETWEEN N'2020-02-3 00:00:00' AND N'2020-02-4 00:00:00'
GROUP BY [USERID]

Better way than CTE

I've written a simple query, but I feel there should be a better way to do it. I'm essentially looking for a way to clean up this code to make it neater and more usable in the future. I will be using this in a few ssrs reports.
DECLARE #Month int = MONTH(GETDATE());
DECLARE #Year int = YEAR(GETDATE());
DECLARE #ThisMth DATE = DATEFROMPARTS(#Year,#Month,1);
DECLARE #BegYear DATE = DATEFROMPARTS(#Year, 7,1);
--EMPLOYEES
With EmpCount AS
(
SELECT
COUNT(DISTINCT(Employee)) As 'DistinctEmployees', PRCo
FROM
PREA
WHERE
Mth = #ThisMth
GROUP BY
PRCo),
TotalEmp AS
(
SELECT
COUNT(DISTINCT(Employee)) As 'TotalDistinctEmployees', PRCo
FROM
PREA
WHERE
Mth >= #BegYear
GROUP BY
PRCo),
Earnings AS
(
SELECT
SUM(Amount) AS Earnings, PRCo
FROM
PREA
WHERE
Mth = #ThisMth AND EDLType = 'E'
GROUP BY
PRCo),
TotalEarnings AS
(
SELECT
SUM(Amount) as TotalEarnings, PRCo
FROM
PREA
WHERE
Mth >= #BegYear and EDLType = 'E'
GROUP BY
PRCo),
Deductions AS
(
SELECT
SUM(Amount) AS Deduction, PRCo
FROM
PREA
WHERE
Mth = #ThisMth AND EDLType = 'D'
GROUP BY PRCo),
TotalDeduction AS
(
SELECT
SUM(Amount) as TotalDed, PRCo
FROM
PREA
WHERE
Mth >= #BegYear AND EDLType = 'D'
GROUP BY
PRCo),
Liabilities AS
(
SELECT
SUM(Amount) AS Liab, PRCo
FROM
PREA
WHERE
Mth = #ThisMth AND EDLType = 'L'
GROUP BY
PRCo),
TotalLiabilities AS
(
SELECT
SUM(Amount) as TotalLiab, PRCo
FROM
PREA
WHERE
Mth >= #BegYear AND EDLType = 'L'
GROUP BY
PRCo)
SELECT
a.PRCo, ec.DistinctEmployees, tem.TotalDistinctEmployees,
e.Earnings, te.TotalEarnings, d.Deduction, td.TotalDed,
l.Liab, tl.TotalLiab, te.TotalEarnings + tl.TotalLiab AS TotalCost
FROM
PREA a
INNER JOIN
EmpCount ec ON ec.PRCo = a.PRCo
INNER JOIN
Earnings e ON e.PRCo = a.PRCo
INNER JOIN
TotalEarnings te ON te.PRCo = a.PRCo
INNER JOIN
TotalEmp tem ON tem.PRCo = a.PRCo
INNER JOIN
Deductions d ON d.PRCo = a.PRCo
INNER JOIN
TotalDeduction td ON td.PRCo = a.PRCo
INNER JOIN
Liabilities l ON l.PRCo = a.PRCo
INNER JOIN
TotalLiabilities tl ON tl.PRCo =a.PRCo
WHERE
Mth = #ThisMth AND EDLType = 'E'
GROUP BY
a.PRCo, ec.DistinctEmployees,e.Earnings, te.TotalEarnings,
tem.TotalDistinctEmployees, d.Deduction, td.TotalDed, l.Liab, tl.TotalLiab
try this:
SELECT PRCo
,COUNT(DISTINCT(CASE WHEN Mth = #ThisMth THEN Employee ELSE NULL END )) As 'DistinctEmployees'
,COUNT(DISTINCT(CASE WHEN Mth >= #BegYear THEN Employee ELSE NULL END )) As 'TotalDistinctEmployees'
,SUM(CASE WHEN Mth = #ThisMth AND EDLType = 'E' THEN Amount ELSE 0 END ) AS Earnings
,SUM(CASE WHEN Mth >= #BegYear and EDLType = 'E' THEN Amount ELSE 0 END) AS TotalEarnings
,SUM(CASE WHEN Mth = #ThisMth AND EDLType = 'D' THEN Amount ELSE 0 END ) AS Deduction
,SUM(CASE WHEN Mth >= #BegYear and EDLType = 'D' THEN Amount ELSE 0 END ) AS TotalDed
,SUM(CASE WHEN Mth = #ThisMth AND EDLType = 'L' THEN Amount ELSE 0 END ) AS Liab
,SUM(CASE WHEN Mth >= #BegYear and EDLType = 'L' THEN Amount ELSE 0 END ) AS TotalLiab
,SUM(CASE WHEN Mth >= #BegYear and EDLType like '[EL]' THEN Amount ELSE 0 END) AS TotalCost
FROM PREA AS p
GROUP BY PRCo

ORA-00937: Not a single-group group function - Query error

Error: ORA-00937: Not a single-group group function
Query:
select count(*) todas,
sum(case when i.prioridade = 1 then 1 else 0 end) urgente,
sum(case when i.prioridade = 2 then 1 else 0 end) alta,
sum(case when i.prioridade = 3 then 1 else 0 end) normal,
sum(case when i.prioridade = 4 then 1 else 0 end) baixa,
(select count(*)
from GMITEMOS i
inner join GMCTLSLA c on c.os = i.cd_numero_os and c.item = i.item
where i.situacao in ('A', 'I', 'P')
and c.ordem = 99999
) naoAvaliados,
sum(case when i.situacao = 'P' then 1 else 0 end) pendentes,
sum(case when i.situacao = 'A' or i.situacao = 'I' then 1 else 0 end) iniciados
from GMITEMOS i
where i.situacao in ('A', 'I', 'P')
and exists (select 1
from GMCTLSLA c
where c.os = i.cd_numero_os
and c.item = i.item)
The error is ocurring here:
(select count(*)
from GMITEMOS i
inner join GMCTLSLA c on c.os = i.cd_numero_os and c.item = i.item
where i.situacao in ('A', 'I', 'P')
and c.ordem = 99999
) naoAvaliados
Can someone tell why is it happening?
You may have fixed it with max but that's not why it's happening and is a little bit hacky. Your problem is that your sub-query, which translates into a single column is not an aggregate query, min, max, sum etc and so needs to be included in a group by clause. You fixed this by wrapping it in max as the maximum of a single value will always be constant.
However, as your sub-query is, itself, an analytic query and will only ever return one row the obvious thing to do is to use a cartesian join to add it to your query. In the explicit join syntax this is known as the cross join.
select count(*) todas
, sum(case when i.prioridade = 1 then 1 else 0 end) urgente
, sum(case when i.prioridade = 2 then 1 else 0 end) alta
, sum(case when i.prioridade = 3 then 1 else 0 end) normal
, sum(case when i.prioridade = 4 then 1 else 0 end) baixa
, naoAvaliados
, sum(case when i.situacao = 'P' then 1 else 0 end) pendentes
, sum(case when i.situacao = 'A' or i.situacao = 'I' then 1 else 0 end) iniciados
from GMITEMOS i
cross join (select count(*) as naoAvaliados
from GMITEMOS j
inner join GMCTLSLA k
on k.os = j.cd_numero_os
and k.item = j.item
where j.situacao in ('A', 'I', 'P')
and k.ordem = 99999
)
where i.situacao in ('A', 'I', 'P')
and exists (select 1
from GMCTLSLA c
where c.os = i.cd_numero_os
and c.item = i.item
)
The cartesian join has a bad reputation as it multiples the number of rows on one side of the join by the number of rows on the other. It does, however, have it's uses, especially in this sort of case.
It's happening because the subquery itself is a scalar result, not a group function. As you have apparently found, you can fix it by substituting a group function that yields an equivalent result to your subquery.
In merge statement, if you are getting this error than simple use the group by and it will resolve the issue.
merge into table1 tb1
using
(select a.id,a.ac_no,sum(a.qy) as qyt,sum(a.amt) as sum_amt from
table2 a, table1 b
where a.id=b.id
and a.id = '1234'
and a.date = '08Oct2014'
and a.ac_no in (123, 234, 345)
and a.ac_no = b.ac_no
group by a.ac_no,a.id
)qry
on (qry.id=tb1.id and qry.ac_no=tb1.ac_no )
when matched then
update set qy=qry.qy,amt = qry.sum_amt;

Implement two filters in one condition - SQL

I am creating a report. In that I am displaying total no of leads, leads sent via Fax and Leads sent via SMS. I wrote a procedure to fetch the records . Here I have to check an condition that both Leads sent via SMS and Leads sent via Fax should not be zero. If both are zero I should not fetch the record. If one of them has any value i should fetch the record. Is it possible implement it through SQL Query.
FROM OP comment to astander
SELECT C.ClientID ,
C.ClientName ,
C.OrganizationName,
C.FirstName ,
S.SMSOverageRate ,
'' as Cost ,
Count(*) as TotalLeads ,
Sum(CASE DeliveryViaFax WHEN 'Y' THEN 1 ELSE 0 END) AS FaxCount ,
Sum(CASE DeliveryViaSMSEmail WHEN 'Y' THEN 1 ELSE 0 END) AS SMSCount
FROM CMN_LeadSaleDetails S INNER JOIN
CMN_LeadClients C ON C.ClientID = S.BuyerID
WHERE C.SellerTenantId = #TenantId
AND S.SellerJournalID = CASE #JournalId WHEN 0 THEN S.SellerJournalID ELSE #JournalId END
GROUP BY C.ClientID ,
C.ClientName ,
C.OrganizationName,
C.FirstName ,
S.SMSOverageRate
You can try something like this
SELECT *
FROM TABLE
WHERE (TotalSMSLeads != 0
OR TotalFaxLeads != 0)
Provide the example query and we can assist you further.
OK, from what you commented i would try something like this
SELECT C.ClientID ,
C.ClientName ,
C.OrganizationName,
C.FirstName ,
S.SMSOverageRate ,
'' as Cost ,
Count(*) as TotalLeads ,
Sum(CASE DeliveryViaFax WHEN 'Y' THEN 1 ELSE 0 END) AS FaxCount ,
Sum(CASE DeliveryViaSMSEmail WHEN 'Y' THEN 1 ELSE 0 END) AS SMSCount
FROM CMN_LeadSaleDetails S INNER JOIN
CMN_LeadClients C ON C.ClientID = S.BuyerID
WHERE C.SellerTenantId = #TenantId
AND S.SellerJournalID = CASE #JournalId WHEN 0 THEN S.SellerJournalID ELSE #JournalId END
GROUP BY C.ClientID ,
C.ClientName ,
C.OrganizationName,
C.FirstName ,
S.SMSOverageRate
HAVING ( Sum(CASE DeliveryViaFax WHEN 'Y' THEN 1 ELSE 0 END) != 0
OR Sum(CASE DeliveryViaSMSEmail WHEN 'Y' THEN 1 ELSE 0 END) != 0)
Alternatively..
Select *
From TABLE
Where (SMSLeads + FaxLeads) > 0
Using your SQL
Select C.ClientID ,C.ClientName ,C.OrganizationName
C.FirstName ,S.SMSOverageRate ,'' as Cost,
Count(*) as TotalLeads ,
Sum(CASE DeliveryViaFax WHEN 'Y' THEN 1 ELSE 0 END) AS FaxCount ,
Sum(CASE DeliveryViaSMSEmail WHEN 'Y' THEN 1 ELSE 0 END) AS SMSCount
FROM CMN_LeadSaleDetails S
INNER JOIN CMN_LeadClients C
ON C.ClientID = S.BuyerID
WHERE C.SellerTenantId = #TenantId
AND S.SellerJournalID = CASE #JournalId WHEN 0 THEN S.SellerJournalID ELSE #JournalId
Group By C.ClientID ,C.ClientName ,C.OrganizationName
C.FirstName ,S.SMSOverageRate
Having (FaxCount+SMSCount) > 0

Resources