Join two tables - sql-server

How can i join these two queries
SELECT
GLMA_COMP_CODE COMP,
GLMA_ACCT_CODE ACCOUNT_NO,
GLMA_DEPT_NO DEPT,
GLMA_ACCT_NAME ACCOUNT_NAME
FROM GLAS_GL_MASTERS
WHERE GLMA_COMP_CODE = #COMP_CODE
AND GLMA_YEAR = CONVERT(NUMERIC(8, 2), DATEPART(YYYY, #DATE_FROM))
AND GLMA_ACCT_CODE BETWEEN ISNULL(#ACCT_CODE_FROM, GLMA_ACCT_CODE) AND
ISNULL(#ACCT_CODE_TO, GLMA_ACCT_CODE)
ORDER BY GLMA_ACCT_CODE
SELECT
GLTR_COMP_CODE,
GLTR_DEPT_NO,
GLTR_ACCT_CODE,
CAST(GLTR_PSTNG_TYPE AS VARCHAR) + CAST(GLTR_PSTNG_NO AS VARCHAR) REF_NO,
CAST(GLTR_DOC_CODE AS VARCHAR) + CAST(GLTR_OUR_DOC_NO AS VARCHAR) DOC_NO,
GLTR_DOC_DATE DOC_DATE,
GLTR_DOC_NARR NARRATIVE,
GLTR_PSTNG_DATE,
CASE SIGN(GLTR_TRAN_AMT)
WHEN + 1 THEN GLTR_TRAN_AMT
ELSE 0
END DEBIT,
CASE SIGN(GLTR_TRAN_AMT)
WHEN - 1 THEN GLTR_TRAN_AMT
ELSE 0
END CREDIT,
GLTR_TRAN_AMT AMOUNT,
GLTR_FC_CODE FC_CODE,
GLTR_FC_AMT FC_AMOUNT
FROM GLAS_GL_TRANSACTIONS
WHERE GLTR_PSTNG_DATE BETWEEN ISNULL(#DATE_FROM, GLTR_PSTNG_DATE) AND ISNULL(#DATE_TO, GLTR_PSTNG_DATE)
ORDER BY GLTR_ACCT_CODE,
GLTR_PSTNG_DATE,
GLTR_DOC_CODE,
GLTR_OUR_DOC_NO

From what's provided, here goes:
SELECT t.gltr_comp_code,
t.gltr_acct_code,
t.gltr_dept_no,
m.glma_acct_name
CAST(t.gltr_pstng_type AS VARCHAR) + CAST(t.gltr_pstng_no AS VARCHAR) REF_NO,
CAST(t.gltr_doc_code AS VARCHAR) + CAST(t.gltr_our_doc_no AS VARCHAR) DOC_NO,
t.gltr_doc_date DOC_DATE,
t.gltr_doc_narr NARRATIVE,
t.gltr_pstng_date,
CASE SIGN(t.gltr_tran_amt) WHEN + 1 THEN t.gltr_tran_amt ELSE 0 END DEBIT,
CASE SIGN(t.gltr_tran_amt) WHEN - 1 THEN t.gltr_tran_amt ELSE 0 END CREDIT,
t.gltr_tran_amt AMOUNT,
t.gltr_fc_code FC_CODE,
t.gltr_fc_amt FC_AMOUNT
FROM GLAS_GL_TRANSACTIONS t
JOIN GLAS_GL_MASTERS m ON m.glma_comp_code = t.gltr_comp_code
AND m.glma_acct_code = t.gltr_acct_code
AND m.glma_dept_no = t.glma_dept_no
WHERE t.gltr_pstng_date BETWEEN COALESCE(#DATE_FROM, t.gltr_pstng_date) AND COALESCE(#DATE_TO, t.gltr_pstng_date)
AND m.glma_comp_code = #COMP_CODE
AND m.glma_year = CONVERT(NUMERIC(8, 2), DATEPART(YYYY, #DATE_FROM))
AND m.glma_acct_code BETWEEN COALESCE(#ACCT_CODE_FROM, t.glma_acct_code) AND COALESCE(#ACCT_CODE_TO, t.glma_acct_code)
ORDER BY t.gltr_acct_code, t.gltr_pstng_date, t.gltr_doc_code, t.gltr_our_doc_no

Related

Issue with >= in the WHERE clause

I'm at my whit's end with this one, frustrated because I'm sure it's something simple and I need a second set of eyes. I've tried this several different ways and I continue to run into an issue where the query will run for a full 24 hours with no results...
I've narrowed the issue down to this section of the query:
WHERE sub.[Savings (%)] >= 10
I ran into so many issues that I ended up nesting the entire query into a sub query, trying to take most of my calculations out of the "Where" clause, but to no effect.
This is all part of a much larger query, so I'll post the abbreviated portion that is relevant.
Here's the very beginning of the query:
SELECT *
FROM
(
SELECT
LD.Region
,DM.ShortName AS DM
,D.Lcode
,LD.locationname
,D.UnitID
,D.dPlaced
,D.dCancelled
,D.sRentalType
,D.[Quoted Rate]
,Calcs.MinStdRate AS [Current Rate]
,-(Calcs.MinStdRate - D.[Quoted Rate]) AS [Savings ($)]
,((-(Calcs.MinStdRate - D.[Quoted Rate]))/NULLIF(D.[Quoted Rate],0))*100 AS [Savings (%)]
,D.sPlanName
,Calcs.[# Vacant]
FROM...
Then this is the WHERE clause at the very end of the query that causes the issue. The entire query beneath "SELECT * FROM" (shown up above) is called "Sub":
) AS sub
WHERE sub.[Savings (%)] >= 10
AND sub.[Current Rate] <> 0
AND sub.[Quoted Rate] <> 0
When I notate "sub.[Savings (%)] >= 10 AND" out of the query, the whole thing runs in about 5 seconds. With it, it runs for hours on end and never produces results...
What am I missing?
Updating to show whole query per request:
SELECT *
FROM
(
SELECT
LD.Region
,DM.ShortName AS DM
,D.Lcode
,LD.locationname
,D.UnitID
,D.dPlaced
,D.dCancelled
,D.sRentalType
,D.[Quoted Rate]
,Calcs.MinStdRate AS [Current Rate]
,-(Calcs.MinStdRate - D.[Quoted Rate]) AS [Savings ($)]
,CAST(((-(Calcs.MinStdRate - D.[Quoted Rate]))/NULLIF(D.[Quoted Rate],0))*100 AS DECIMAL (18,2)) AS [Savings (%)]
,D.sPlanName
,Calcs.[# Vacant]
FROM
(SELECT
s.sLocationCode AS lcode
,w.dPlaced
,L.dLease
,u.UnitID
,CASE
WHEN w.dCancelled IS NOT NULL THEN w.dCancelled
WHEN (w.dCancelled IS NULL AND w.dExpires <GETDATE()) THEN w.dExpires
ELSE NULL
END AS dCancelled
,CASE
WHEN (w.dCancelled IS NOT NULL OR w.dExpires <GETDATE()) THEN 'Lost'
WHEN w.QTRentalTypeID = 3 THEN 'Rented'
WHEN (w.QTRentalTypeID = 2 OR w.QTRentalTypeID = 1) THEN 'Active'
END AS sRentalType
,w.dcRate_Quoted AS 'Quoted Rate'
,c.sPlanName
,CONCAT(U.dcWidth,'x',U.dcLength) AS sSize
,UT.sTypeName
FROM CompanyDBs.dbo.waitings AS W
LEFT OUTER JOIN CompanyDBs.dbo.Ledgers AS L
ON W.LedgerID = L.LedgerID
JOIN CompanyDBs.dbo.sites AS S
ON W.SiteID = S.SiteID
JOIN CompanyDBs.dbo.units AS U
ON W.UnitID1 = U.UnitID
JOIN CompanyDBs.dbo.UnitTypes AS UT
ON U.UnitTypeID = UT.UnitTypeID
JOIN CompanyDBs.dbo.ConcessionPlans AS C
ON W.ConcessionID = C.ConcessionID
WHERE W.dCancelled < GETDATE() AND W.dCancelled >= DATEADD(DD,-60,CAST(GETDATE() AS DATE))
UNION ALL
SELECT
s.sLocationCode AS lcode
,w.dPlaced
,L.dLease
,u.UnitID
,CASE
WHEN w.dCancelled IS NOT NULL THEN w.dCancelled
WHEN (w.dCancelled IS NULL AND w.dExpires <GETDATE()) THEN w.dExpires
ELSE NULL
END AS dCancelled
,CASE
WHEN (w.dCancelled IS NOT NULL OR w.dExpires <GETDATE()) THEN 'Lost'
WHEN w.QTRentalTypeID = 3 THEN 'Rented'
WHEN (w.QTRentalTypeID = 2 OR w.QTRentalTypeID = 1) THEN 'Active'
END AS sRentalType
,w.dcRate_Quoted AS 'Quoted Rate'
,c.sPlanName
,CONCAT(U.dcWidth,'x',U.dcLength) AS sSize
,UT.sTypeName
FROM CompanyDBs1.dbo.waitings AS W
LEFT OUTER JOIN CompanyDBs1.dbo.Ledgers AS L
ON W.LedgerID = L.LedgerID
JOIN CompanyDBs1.dbo.sites AS S
ON W.SiteID = S.SiteID
JOIN CompanyDBs1.dbo.units AS U
ON W.UnitID1 = U.UnitID
JOIN CompanyDBs1.dbo.UnitTypes AS UT
ON U.UnitTypeID = UT.UnitTypeID
JOIN CompanyDBs1.dbo.ConcessionPlans AS C
ON W.ConcessionID = C.ConcessionID
WHERE W.dCancelled < GETDATE() AND W.dCancelled >= DATEADD(DD,-60,CAST(GETDATE() AS DATE))) AS D
LEFT OUTER JOIN
(SELECT
P.SiteID
,P.sLocationCode
,P.UnitID
,p.UnitCODE
,groupeddata.[# Vacant]
,GroupedData.MinStdRate
FROM
(SELECT
S2.sLocationCode
,S2.SiteID
,R2.UnitID
,CONCAT(S2.sLocationCode
,'-'
,S2.sSiteName
,' '
,R2.stypename
,' '
,CASE WHEN R2.iFloor > 1 THEN 'Up ' WHEN R2.ifloor < 1 THEN 'Down ' WHEN R2.ifloor = 1 THEN '1 ' END
,CASE WHEN R2.bPower = 1 THEN 'Power ' ELSE 'No Power ' END
,CASE WHEN R2.bClimate = 1 THEN 'CC ' ELSE 'No CC ' END
,CASE WHEN R2.bInside = 1 THEN 'In ' ELSE 'Out ' END
,CASE WHEN R2.bAlarm = 1 THEN 'Alarm ' ELSE 'No Alarm ' END
,CAST(R2.dcWidth AS FLOAT)
,'x'
,CAST(R2.dcLength AS FLOAT)) AS UnitCODE
FROM Operations.dbo.RentRoll AS R2
JOIN
(
SELECT *
FROM CompanyDBs.dbo.sites
UNION ALL
SELECT *
FROM CompanyDBs1.dbo.sites
) AS S2
ON R2.siteid = S2.SiteID
WHERE
R2.ddeleted is NULL
AND R2.bRentable = 1
AND R2.brented = 0 ) AS P
JOIN
(
SELECT
S.SiteID
,s.sLocationCode
,UnitCode.UnitCODE
,SUM(CASE
WHEN R.brented = 1 THEN 0
ELSE 1
END) AS [# Vacant]
,MIN(R.dcStdRate) AS MinStdRate
FROM Operations.dbo.RentRoll AS R
JOIN
(
SELECT *
FROM CompanyDBs.dbo.sites
UNION ALL
SELECT *
FROM CompanyDBs1.dbo.sites
) AS S
ON R.siteid = S.SiteID
JOIN
(
SELECT
S1.SiteID
,UnitID
,CONCAT(S1.sLocationCode
,'-'
,S1.sSiteName
,' '
,R1.stypename
,' '
,CASE WHEN R1.iFloor > 1 THEN 'Up ' WHEN R1.ifloor < 1 THEN 'Down ' WHEN R1.ifloor = 1 THEN '1 ' END
,CASE WHEN R1.bPower = 1 THEN 'Power ' ELSE 'No Power ' END
,CASE WHEN R1.bClimate = 1 THEN 'CC ' ELSE 'No CC ' END
,CASE WHEN R1.bInside = 1 THEN 'In ' ELSE 'Out ' END
,CASE WHEN R1.bAlarm = 1 THEN 'Alarm ' ELSE 'No Alarm ' END
,CAST(R1.dcWidth AS FLOAT)
,'x'
,CAST(R1.dcLength AS FLOAT)) AS UnitCODE
FROM Operations.dbo.RentRoll AS R1
JOIN
(
SELECT *
FROM CompanyDBs.dbo.sites
UNION ALL
SELECT *
FROM CompanyDBs1.dbo.sites
) AS S1
ON R1.siteid = S1.SiteID
) AS UnitCode
ON CONCAT(R.siteid, R.unitid) = CONCAT(UnitCode.siteid,UnitCode.UnitID)
WHERE
s.sLocationCode <> 'L003'
AND s.sLocationCode <> 'L021'
AND s.sLocationCode <> 'LSETUP'
AND s.sLocationCode <> 'LTRAIN'
AND R.bRented = 0
GROUP BY s.siteid, s.slocationcode, UnitCode.UnitCODE
) AS GroupedData
ON P.UnitCODE = GroupedData.UnitCODE
) AS Calcs
ON CONCAT(D.lcode,D.unitid) = CONCAT(Calcs.slocationcode,Calcs.unitid)
JOIN operations.dbo.westport_locationdata AS LD
ON D.lcode = ld.lcode
JOIN operations.dbo.Westport_DMs AS DM
ON LD.DMID = DM.DMID
) AS sub
WHERE sub.[Savings (%)] >= CAST(10.0 AS DECIMAL (18,2))
AND sub.[Current Rate] <> 0
AND sub.[Quoted Rate] <> 0
Unfortunately you are posting not the whole query. I could image that some indexes are missing.
I give you the strong advice to run your query in SQL Server Management Studio with the option "Query" -> "Include Actual Execution Plan" checked.
With this, SSMS will execute the query and tell you afterwards if indexes are missing and how much you could improve by setting them. You will get also a picture oh how the query is running.
Cast your where clause filter value WHERE sub.[Savings (%)] >= cast(10.0 as decimal(18,2)) so there isn't an implicit conversion from int to decimal.
https://learn.microsoft.com/en-us/sql/t-sql/data-types/data-type-conversion-database-engine?view=sql-server-ver15#:~:text=Implicit%20conversions%20are%20not%20visible,converts%20to%20date%20style%200.

Add symbol to Row values of select query output

I have transposed results of a select query through PIVOT to get the results as shown below. All the values are in decimal(18,1) format.
|| Item1 || Item2 || Item3
Avg_Price || 234 || 156 || 73
%share || 17 || 3 || 35
I need to add $ and % symbols to th rows Avg_Price and %share, respectively. How can I achieve this?
EDIT: Giving the PIVOT query here, as requested by #B3S.
select [Name], [Item1],[Item2],[Item3],[Total]
from
(
select [Item_Type], [Name], value
from (select [Item_Type],[Total Sales],[Share of Total Sales],[Average Price],[$0 to $99],[$100 to $199],[$200+]
from (SELECT [Item_Type],[Total Sales],CAST([Total Sales]*100.0/(SELECT SUM([Total Sales]) FROM My_DB.dbo.Sales_Data GROUP BY [Year],[Month]) AS DECIMAL(38,1)) [Share of Total Sales],[Average Price],[$0 to $99],[$100 to $199],[$200+]
FROM My_DB.dbo.Sales_Data
union all
select 'Total',SUM([Total Sales]),SUM([Total Sales])*100.0/(SELECT SUM([Total Sales]) FROM My_DB.dbo.Sales_Data GROUP BY [Year],[Month]) [Share of Total Sales],CAST(AVG([Average Price]) AS DECIMAL(38,1)),SUM([$0 to $99]),SUM([$100 to $199]),SUM([$200+])
from My_DB.dbo.Sales_Data
GROUP BY [Year],[Month]) d
) e
unpivot
(
value for [Name] in ([Total Sales],[Share of Total Sales],[Average Price],[$0 to $99],[$100 to $199],[$200+])
) unpiv
) src
pivot
(
sum(value)
for [Item_Type] in ( [Item1],[Item2],[Item3],[Total])
) piv;
EDIT: It is not a duplicate question. It is a different question to the one being pointed here. I had posted this question to seek an efficient way of updating values in a row instead of querying every single value and appending it.
Wrap your [Item1] etc. with some string manipulation.
declare #i int = 1
select '$' + convert(varchar, #i * 1.00)
select convert(varchar, #i) + '%'
You may need something like:
SELECT [Name],
CASE WHEN [Name] = 'Avg_Price' THEN '$' + convert(varchar, [Item1] * 1.00)
ELSE convert(varchar, [Item1]) + '%'
END AS [Item1],
CASE WHEN [Name] = 'Avg_Price' THEN '$' + convert(varchar, [Item2] * 1.00)
ELSE convert(varchar, [Item2]) + '%'
END AS [Item2],
... etc...

Getting a max date using various groups in a select in SQL Server

Been stuck on this. I have the query and the result set below:
DECLARE #bookdate date = cast(DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), - 1) AS DATE)
DECLARE #offset int = 1
SELECT distinct #bookdate BookDate
,th.Transactioncd TransactionType
,bp.PolicyNumber PolicyNumber
,cast(bp.EffectiveDt AS DATE) EffectiveDate
,cast(th.TransactionEffectiveDt AS DATE) TransactionEffectiveDate
,NULL
,th.TransactionNumber TransactionNumber
,cast(bp.ExpirationDt AS DATE) ExpirationDate
,UPPER(ni.IndexName) InsuredName
,isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), '') InsuredStreetAddress
,UPPER(ad.City) InsuredCity
,UPPER(ad.StateProvCd) InsuredState
,ad.PostalCode InsuredZipCode
,i.EntityTypeCd InsuredType
,isnull(tr.ReasonCd, '') ReasonCode
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4)) ProrateFactor
,'0'
,'0'
,'0'
,bd.YearBuilt YrConstruction
,ln.PROPDed + '%' [% loss ded EQ]
,CAST(bd.BldgNumber AS VARCHAR(255)) BldgNumber
,CONVERT(INT,REPLACE(bd.BuildingValue,',','')) BuildingValue
,CONVERT(INT,REPLACE(bd.ContentsBLimit,',','')) ContentsBLimit
,CONVERT(INT,REPLACE(bd.ContentsCLimit,',','')) ContentsCLimit
,CONVERT(INT,REPLACE(bd.TIBLimit,',','')) TIBLimit
,CONVERT(INT,REPLACE(bd.BILimit,',','')) BILimit
,CONVERT(INT,REPLACE(bd.EDPLimit,',','')) EDPLimit
FROM java.basicpolicy bp
INNER JOIN java.nameinfo ni ON ni.SystemId = bp.SystemId
AND ni.CMMContainer = bp.CMMContainer
INNER JOIN java.partyinfo pti on pti.Id=ni.ParentId
AND pti.CMMContainer=bp.CMMContainer
and pti.SystemId=bp.SystemId
INNER JOIN java.line ln ON ln.CMMContainer = bp.CMMContainer
AND bp.SystemId = ln.SystemId
INNER JOIN java.risk r on r.SystemId=bp.SystemId
AND r.CMMContainer=bp.CMMContainer
AND r.ParentId=ln.Id
INNER JOIN java.building bd ON bd.CMMContainer = bp.CMMContainer
AND bd.SystemId = bp.SystemId
AND bd.ParentId=r.id
AND bd.[Status] = 'ACTIVE'
INNER JOIN java.addr ad ON ad.CMMContainer = ni.CMMContainer
AND bp.SystemId = ad.SystemId
AND ad.AddrTypeCd in ('RiskAddr')
AND ad.ParentId = bd.id
INNER JOIN java.transactioninfo th ON th.CMMContainer = bp.CMMContainer
AND th.SystemId = bp.SystemId
LEFT JOIN java.transactionreason tr ON tr.CMMContainer = bp.CMMContainer
AND TR.SystemId = bp.SystemId
AND TR.ParentId = th.ID
INNER JOIN java.insured i ON i.CMMContainer = bp.CMMContainer
AND i.SystemId = bp.SystemId
WHERE bp.CMMContainer = 'Application'
AND ni.NameTypeCd = 'INSUREDNAME'
AND (
th.TransactionCd IN (
'new business'
,'endorsement'
,'cancellation'
,'rewrite-new'
)
OR (
th.WrittenPremiumAmt IS NOT NULL
AND th.WrittenPremiumAmt <> 0
AND th.TransactionCd IN ('reinstatement')
)
)
AND bp.CarrierCd = 'ENIC'
AND th.TransactionEffectiveDt not like '2016-12%'
GROUP BY
th.Transactioncd
,bp.PolicyNumber
,cast(bp.EffectiveDt AS DATE)
,cast(th.TransactionEffectiveDt AS DATE)
,th.TransactionNumber
,cast(bp.ExpirationDt AS DATE)
,UPPER(ni.IndexName)
,isnull(UPPER(ad.Addr1), '') + ' ' + isnull(UPPER(ad.Addr2), '') + ' ' + isnull(UPPER(ad.Addr3), '') + ' ' + isnull(UPPER(ad.Addr4), '')
,UPPER(ad.City)
,UPPER(ad.StateProvCd)
,ad.PostalCode
,i.EntityTypeCd
,isnull(tr.ReasonCd, '')
,cast(datediff(mm, th.transactioneffectivedt, bp.expirationdt) / cast(datediff(mm, bp.effectivedt, bp.expirationdt) AS DECIMAL(15, 4)) AS DECIMAL(15, 4))
,bd.YearBuilt
,ln.PROPDed + '%'
,CAST(bd.BldgNumber AS VARCHAR(255))
,CONVERT(INT,REPLACE(bd.BuildingValue,',',''))
,CONVERT(INT,REPLACE(bd.ContentsBLimit,',',''))
,CONVERT(INT,REPLACE(bd.ContentsCLimit,',',''))
,CONVERT(INT,REPLACE(bd.TIBLimit,',',''))
,CONVERT(INT,REPLACE(bd.BILimit,',',''))
,CONVERT(INT,REPLACE(bd.EDPLimit,',',''))
ORDER BY PolicyNumber, transactionnumber, bldgnumber
I get this result set:
What I want is to remove the duplicated transaction number 2 as you can see on the picture. I tried doing the max and group by function using the date and it didn't work. I tried it on transaction number, it works but introduced other problems. Is there anyway that I can get one result set? It is not a real duplicate, it has a different date but I only want to get the latest date that's why I figured the max function might work but I have to group by everything and that didn't help much. I have been looking at outer apply but I have never used that and I don't even know how I would use that on this particular problem.
Have you tried first_value?
FIRST_VALUE ( [scalar_expression ] )
OVER ( [ partition_by_clause ] order_by_clause [ rows_range_clause ] )
it works like this: you need to write DISTINCT
select **distinct** id,
first_value(transaction_effective_date) over (partition by number (,sup) order by date DESC (latest, ASC for oldest)) as last_trans_date
from table;
Documentation can be found here: https://msdn.microsoft.com/en-us/library/hh213018.aspx

Not writing a value in XML with SQL Server

I have the following query which is part of a bigger XML. The issue is that is not writing the 0 value of the ELSE and writes an empty element <SellingLocation> in the XML. I can't find why. This is the query code.
SELECT (
SELECT TOP 1
CASE WHEN COUNT(ac.SKU) > 0
THEN l.ZoneId + ' ' + SUBSTRING(CONVERT(varchar(10), l.Bays), 0, 4)
ELSE 0
END
FROM #ARTSCreditTrans ac
INNER JOIN LocationSKU l ON ac.SKU = l.SKU
WHERE ac.PickTake = 'P'
GROUP BY ZoneId, Bays
)
FOR XML PATH('SellingLocation'), TYPE
#Devart, how can I make the same modification in the case of a query which has more that one option and the filter with the having doesn't look like the solution? For example:
SELECT [text()] = ISNULL((
SELECT TOP 1
CASE WHEN COUNT(oh.OrderNumber) > 0
THEN oh.Latitude
ELSE CASE WHEN td.RegisterID = 80
THEN SUBSTRING(tt.ShipMidInit, 1, CHARINDEX('|', tt.ShipMidInit) - 1)
END
END
FROM OrderHeader oh INNER JOIN TranDetail td ON oh.OrderNumber = td.DocNumber JOIN TranTotal tt ON td.DocNumber = tt.DocNumber
WHERE td.PickTake = 'P'
GROUP BY oh.Latitude, td.RegisterID, tt.ShipMidInit
), '')
FOR XML PATH('Latitude'), TYPE
Try wrapping the 0 in quotes ('):
SELECT (
SELECT TOP 1
CASE WHEN COUNT(ac.SKU) > 0
THEN l.ZoneId + ' ' + SUBSTRING(CONVERT(varchar(10), l.Bays), 0, 4)
ELSE '0'
END
FROM #ARTSCreditTrans ac INNER JOIN LocationSKU l ON ac.SKU = l.SKU
WHERE ac.PickTake = 'P'
GROUP BY ZoneId, Bays
)
FOR XML PATH('SellingLocation')
, TYPE
SELECT [text()] = ISNULL((
SELECT TOP 1 CAST(l.ZoneId AS VARCHAR(100)) + ' ' + CAST(l.Bays AS VARCHAR(5))
FROM #ARTSCreditTrans ac
JOIN dbo.LocationSKU l ON ac.SKU = l.SKU
WHERE ac.PickTake = 'P'
GROUP BY ZoneId, Bays
HAVING COUNT(ac.SKU) > 0
), '0')
FOR XML PATH('SellingLocation'), TYPE

Group By OrgName but rollup by TotalCount

I would like to use the code below to group results by OrgName but rollup the count using TotalCount
Results would look similar to the screenshot below:(sorry I had to redact information due to confidentiality agreement).
The Orgname is grouped correctly. However, I am having a little troubling rolling up totalCount.
Thanks
WITH
ctePreAgg AS
(
SELECT (ElectionName + ' - ' + CAST(ClosingDate AS VARCHAR(12))) electionName, CASE WHEN Position='Member' THEN '' ELSE Position END As Position, CASE WHEN c.CurrentOfficeHolder='Incumbent' THEN CandidateName + '('+ c.CurrentOfficeHolder + ')' ELSE CandidateName END As CandidateName , c.PositionId,COUNT(*) TotalVotes
FROM Candidates c
JOIN Positions p ON c.PositionId = p.PositionId
JOIN Elections e on c.ElectionId = e.ElectionId
WHERE c.ElectionId IN (1,2,3)
GROUP BY Position, CandidateId, CandidateName,c.PositionId,CurrentOfficeHolder,AnswerType,ElectionName, ClosingDate
)
SELECT [OrgName] = CASE WHEN GROUPING(mh.PositionId) = 0 THEN MAX(mh.Position) ELSE mh.ElectionName END
,Names = CASE WHEN GROUPING(mh.PositionId) = 0 THEN MAX(mh.CandidateName) ELSE '' END
,PositionId = CASE WHEN GROUPING(mh.PositionId) = 0 THEN mh.PositionId ELSE '' END
,TotalCount = CASE WHEN GROUPING(mh.PositionId) = 0 THEN COUNT(*) ELSE '' END
FROM ctePreAgg mh
GROUP BY ElectionName,PositionId WITH ROLLUP
HAVING GROUPING(mh.ElectionName) = 0
ORDER BY mh.ElectionName, GROUPING(mh.PositionId) DESC, mh.PositionID;

Resources