SQL - Summing aggregate sub query - sql-server

This is the code I have
select distinct sli.order_no,
sli.pkg_no,
case when line.primary_ind = 'Y' then sum(paid_amt) else 0 end as paid_amt,
line.pkg_li_no,
sum(case when sli.perf_no = 0 then 1 else 0 end) as num_seats_pur,
sli.status
from t_sub_line sli
left outer join t_line line on sli.li_seq_no = line.li_seq_no
where sli.order_no in (1,2)
group by
sli.order_no,
sli.pkg_no,
line.primary_ind,
line.pkg_li_no,
sli.status
having line.primary_ind = 'Y'
This code produces this output
order_no pkg_no paid_amt pkg_li_no num_seats_pur status
1 322 124.00 967 2 7
1 322 -124.00 992 2 4
2 854 253.00 952 1 7
2 854 -253.00 996 1 4
what I really need for the data to return is the following. I need the sum of paid_amt field.
order_no pkg_no paid_amt pkg_li_no num_seats_pur status
1 322 0 967 2 7
2 854 0 996 1 4
even if i change status to be max(status) so its not grouping on it. I don't have sum_paid amt.
when i try this code:
sum(case when line.primary_ind = 'Y' then sum(paid_amt) else 0 end) as paid_amt,
I get the following error message
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

A couple things you need to do.
Comment out pkg_li_no from the select and group by
Change the having statement to be included in the where statement
Remove the case from paid_amt since it is not necessary
select distinct sli.order_no,
sli.pkg_no,
sum(paid_amt)as paid_amt,
-- line.pkg_li_no,
sum(case when sli.perf_no = 0 then 1 else 0 end) as num_seats_pur,
sli.status
from t_sub_line sli
left join t_line line on sli.li_seq_no = line.li_seq_no
where sli.order_no in (1,2)
and line.primary_ind = 'Y'
group by
sli.order_no,
sli.pkg_no,
line.primary_ind,
-- line.pkg_li_no,
sli.status
Other notes:
I am not sure you want to select or group by the pkg_no or status, but you know more what outcome are looking for. If they are different values, there will be different records.

I'm not sure what you're trying to accomplish, but it seems that you overthinking the query. Try to simplifying it.
FYI HAVING happens after the grouping, WHERE happens before the grouping, you don't even need the CASE
select distinct sli.order_no,
sli.pkg_no,
sum(paid_amt) as paid_amt,
sum(case when sli.perf_no = 0 then 1 else 0 end) as num_seats_pur,
sli.status
from t_sub_line sli
left outer join t_line line on sli.li_seq_no = line.li_seq_no
where sli.order_no in (1,2)
and line.primary_ind = 'Y'
group by
sli.order_no,
sli.pkg_no,
sli.status

Related

SUM() with entries from 2 table

Select p.pnum,
SUM(CASE WHEN P.NegativeScreen = 'Type99' THEN 1 ELSE 0 END) TotalDetected,
SUM(IIF(P.IsPositive = 1, 1,0)) TotalP,
SUM(CASE WHEN (P.MethId NOT IN (4, 8, 10, 25) THEN 1 ELSE 0 END) Total,
SUM(CASE WHEN (P.MethID IN (34,64) ) THEN 1 ELSE 0 END) TotalVal1,
SUM(CASE WHEN (P.MethID IN (16,64) ) THEN 1 ELSE 0 END) TotalVal2,
SUM(CASE WHEN (P.MethID IN (2,4,6,11,13,14,15,18,21,22,24,28,30,31) OR (P.MethID
= 1 AND P.TotalCount IS NOT NULL)) THEN 1 ELSE 0 END) TotalMethOther,
FROM tbl_plt p
GROUP BY P.PNum
Notice that the above query has all the fields from the tbl_plt table and SUM() is done on the fields.
Notice where I have MethID mentioned above. I need to check if those MethID exist in the tbl_plt table and if they exist in another table called TblOther. If so, tally it up accordingly.
Here is the fields in TblOther Table. Note that in TblOther table, we can have multiple PNums but the MethID will be different. Also note that for not all pNums will have entries in the TblOther table.
ID PNum MethID
1 232 32
2 232 64
3 232 10
4 104 14
5 104 54
6 22 4
7 4 13
I tried with LEFT JOIN with TblOther table but things gets messy as with the left join, it also tallies up incorrectly for places like:
SUM(CASE WHEN P.NegativeScreen = 'Type99' THEN 1 ELSE 0 END) TotalDetected,
SUM(IIF(P.IsPositive = 1, 1,0)) TotalP,
As an example for where I have:
SUM(CASE WHEN (P.MethID IN (34,64) ) THEN 1 ELSE 0 END)
it needs get the count of how many MethID exist in both the tblOther and tbl_plt for where MethID is 34 or 64 for the associated PNum.
It needs to do similarly for other places where MethID is mentioned.
I don't know enough about TblOther or it's join, but I suspect you might need to do the same group by (i.e., PNum) on it before joining on PNum. Then the left join will match either 0 or 1 records. Be sure to account for the null if there is no match.
You could start by getting the list of distinct PNum and MethIDs to use and then do your summing based on that list:
;WITH entries as (
SELECT DISTINCT PNum, MethID
FROM tblOther)
SELECT *
FROM entries
INNER JOIN tbl_plt
ON entries.PNum = tbl_plt.PNum
AND entries.MethID = tbl_plt.MethID
GROUP BY entries.PNum

How to flatten this multiple rows into one?

I have data like this: (table name: Activities)
ActivityId CreatedOn TypeId
1 2017-01-01 1
1 2017-01-02 1
1 2017-01-02 2
2 2017-01-01 3
Where Type is a lookup value: (table name: Types)
TypeId Name
1 Question
2 Answer
3 Comment
Basically it's an activity history table.
I want to turn the above tables into a grouped sum row for types, for each ActivityId, like this:
ActivityId QuestionCount AnswerCount CommentCount
1 2 1 0
2 0 0 1
I know the answer is probably pretty simple, but it's eluding me for some reason.
Any help? Thanks in advance.
A simple join and conditional aggregation should do the trick (I suspect you were over-thinking it)
Select ActivityID
,QuestionCount = sum(case when Name='Question' then 1 else 0 end)
,AnswerCount = sum(case when Name='Answer' then 1 else 0 end)
,CommentCount = sum(case when Name='Comment' then 1 else 0 end)
From Activities A
Join Types B on A.TypeId=B.TypeId
Group By ActivityId
Returns
ActivityID QuestionCount AnswerCount CommentCount
1 2 1 0
2 0 0 1
You could also do it without the Join... Just less readable
Select ActivityID
,QuestionCount = sum(case when TypeId=1 then 1 else 0 end)
,AnswerCount = sum(case when TypeId=2 then 1 else 0 end)
,CommentCount = sum(case when TypeId=3 then 1 else 0 end)
From #Activities A
Group By ActivityId
You could also try a PIVOT
Select ActivityID
,[1] as QuestionCount
,[2] as AnswerCount
,[3] as CommentCount
From (Select ActivityId,TypeID,1 as Cnt From #Activities) A
Pivot (count(Cnt) For TypeId in ([1],[2],[3]) ) p

COUNT and COUNT DISTINCT for different groups

For a SQL Server based report,
Table:
CID Date ID Service Days
1 3/7/2016 1 Individual 3
2 4/5/2016 2 Individual 4
3 5/24/2016 1 Individual 3
4 4/4/2016 4 Group 2
5 4/4/2016 4 Group 2
6 2/18/2016 4 Group 2
7 5/5/2016 5 Group 1
8 5/5/2016 5 Group 1
I used this code:
SELECT
ID,
Service,
COUNT(WHEN Days = 4 THEN 1 END) AS '4Days',
COUNT(WHEN Days = 3 THEN 1 END) AS '3Days',
COUNT(WHEN Days = 2 THEN 1 END) AS '2Days',
COUNT(WHEN Days = 1 THEN 1 END) AS '1Day'
FROM Table T1
GROUP BY
ID,
Service
which gives me this Output:
ID Service 4Days 3Days 2Days 1Day
1 Individual 0 2 0 0
2 Individual 1 0 0 0
4 Group 0 0 3 0
5 Group 0 0 0 2
What I want to do is not count the Group services as separate services for separate individuals, but just as one service per group. A Count Distinct used with the Date or ID could help me do that but I don't know how to make that play with the Individual services where I just wanna count them individually and not using DISTINCT. So the desired output is:
ID Service 4Days 3Days 2Days 1Day
1 Individual 0 2 0 0
2 Individual 1 0 0 0
4 Group 0 0 2 0
5 Group 0 0 0 1
I'll edit the post in case I oversimplified the problem since this is dummy data.
Looks like you could use distinct this way if you wanted:
count(distinct
case when Days = 1 then case when Service = 'Group' then 1 else "Date" end end
) as [1Day]
Depending on your indexing it's possible that introducing another column in the query would change the query plan. I suspect that probably isn't the case though.
If I am not wrong for '2Days' column service type 'Group' count should be '2' if our grouping based on 'Date' column, if so then try this:
SELECT
ID,
Service,
CASE WHEN MAX(t.days) = 4 THEN MAX(t.date) ELSE 0 END AS '4Days',
CASE WHEN MAX(t.days) = 3 THEN MAX(t.date) ELSE 0 END AS '3Days',
CASE WHEN MAX(t.days) = 2 THEN MAX(t.date) ELSE 0 END AS '2Days',
CASE WHEN MAX(t.days) = 1 THEN MAX(t.date) ELSE 0 END AS '1Day'
FROM table T1
OUTER APPLY (SELECT days,
COUNT(DISTINCT(date)) date
FROM Table WHERE days = t1.days GROUP BY days) t
GROUP BY id, service
ORDER BY ID
Based on your last edit, this is the most straight forward way I could think of to handle the query:
with cte as (
select id, service, days
from table t1
where service = 'Individual'
union all
select id, service, days
from table t1
where service = 'Group'
group by id, service, days, date
)
select id,
service,
count(case when days = 4 then 'X' end) as [4Days],
count(case when days = 3 then 'X' end) as [3Days],
count(case when days = 2 then 'X' end) as [2Days],
count(case when days = 1 then 'X' end) as [1Day]
from cte
group by id, service

Calculate Type of the member in a table (Self Join/Case When or any other possible way)

Here is the Table :
If OBJECT_ID ('tempdb..##SelfCount') Is not null
drop table #SelfCount
create table #SelfCount (CanID int , CanType int)
insert into #SelfCount (CanID, CanType)
values
(1,0),
(2,0),
(1,1),
(2,1),
(1,2),
(1,2),
(1,0)
CanID CanType
1 0
2 0
1 1
2 1
1 2
1 2
1 0
I'm Expecting the result to be like this
CanID Self Spouse Dependent
1 2 1 2
2 1 1 0/NULL --It doesn't matter if it's nUll or 0
I wrote this query
select CanID,
case
When CanType = 0 then count(CanType)
end as [self],
case
when CanType = 1 then count(CanType)
end as [Spouse],
Case
When CanType = 2 then count(CanType)
end as [Dependent]
from #SelfCount
Group by CanID, CanType
But the Result Set is like this :
CanID Self Spouse Dependent
1 2 NULL NULL
2 1 NULL NULL
1 NULL 1 NULL
2 NULL 1 NULL
1 NULL NULL 2
I've tried the Recursive method, If anyone could provide both Recursive as well as Set processing method, it'll be greatly appreciated.
By including the CanType in the group by clause, you're getting a separate result row per distinct value of CanType (and CanId, since it's also contained in the group by clause).
Instead, you should only have CanId in the group by clause, and apply different counts on case expressions:
SELECT CanID,
COUNT (CASE CanType WHEN 0 THEN 1 END) AS [Self],
COUNT (CASE CanType WHEN 1 THEN 1 END) AS [Spouse],
COUNT (CASE CanType WHEN 2 THEN 1 END) AS [Dependent],
FROM #SelfCount
GROUP BY CanID
May be this is what you need:
select CanID,
sum(case when CanType = 0 then 1 else 0 end) as [Self],
sum(case when CanType = 1 then 1 else 0 end) as [Spouse],
sum(case when CanType = 2 then 1 else 0 end) as [Dependent]
from #SelfCount
group by CanID
You can try with PIVOT:
select
CanID,
[0] as Self,
[1] as Spouse,
[2] as Dependent
from tab
pivot
(
count (CanType)
for CanType IN ([0], [1], [2])
) as pvt
Basically, it will group by all columns not declared inside the PIVOT clause (actually, just the CanID) and then create three aggregation COUNT columns, one FOR each CanType IN the list of values. If you need to count more values, just define them in the IN clause and in the SELECT clause.

SQL Server Left Outer Join returns either too many rows or incorrect rows

I have a SQL Server query that I want to do a left join to 2 tables. I need it to return all of the rows in the 1st table and only the matching data in the other 2 tables. My first incarnation created some sort of cross product with more than 10 times the required rows. So I added a rowcount function and had it filter for all rowcount values = 1. Now it returns the correct number of rows but with the wrong data from the other 2 tables.
I have certain filter rules (case statements) I apply to the contents of the 2 right tables to determine what, if anything, to return. I think this may be the source of the problem, but I'm not sure. I've tried using the filter code both within the select statement and as a where statement at the end of the query and even as part of the join on statement. I also tried using cross and outer applies. All to no avail.
I'm trying to achieve this without using loops. Is it possible? Please see the code below. This code generates too many rows. I won't repeat the 2nd iteration as it adds an extra select on top and a filter for m= 1 to the bottom to generate the correct number of rows.
These are the 2 tables that I am left joining to. Note that the 2nd table is only a small subset of a much larger table.
Thanks!!!
SELECT
GLENTRY.Fac + GLENTRY.Rundt + GLENTRY.Jrnllog AS UniqueID,
GLENTRY.Fac AS Fac,
(CASE WHEN
EntityTranslate2014.AcctEnd <> '' AND EntityTranslate2014.AcctEnd = SUBSTRING(GLENTRY.Acct,6,3)
THEN
EntityTranslate2014.Entity
ELSE
CASE WHEN
EntityTranslate2014.AcctEnd <> 0 AND EntityTranslate2014.Acct = GLENTRY.Acct
THEN
EntityTranslate2014.Entity
ELSE
CASE WHEN
EntityTranslate2014.SSDept <> 0 AND EntityTranslate2014.SSDept = SUBSTRING(GLENTRY.Acct,1,4)
THEN
EntityTranslate2014.Entity
ELSE
CASE WHEN
EntityTranslate2014.SSDept = 0
AND
EntityTranslate2014.AcctEnd = ''
AND
EntityTranslate2014.Acct = 0
THEN
EntityTranslate2014.Entity
ELSE
''
END
END
END
END)
AS NEWEntity,
(CASE WHEN AcctTranslate2014.Fac = GLENTRY.Fac OR AcctTranslate2014.Fac = '0'
THEN
AcctTranslate2014.NEWDept
ELSE
Null
END)
AS Department,
(CONVERT(DATETIME,GLENTRY.Period + '/01/' +
CASE WHEN
CONVERT(NVARCHAR(4),GLENTRY.Yearz) = ''
THEN
'2014'
ELSE
GLENTRY.Yearz
END)
AS YEARPER,
GLENTRY.Acct) AS SSAcct,
CONVERT(NVARCHAR(20),
CASE WHEN
AcctTranslate2014.Fac = GLENTRY.Fac OR AcctTranslate2014.Fac = '0'
THEN
AcctTranslate2014.NEWAcct
ELSE
Null
END)
AS NEWAccount,
GLENTRY.Rundt,
GLENTRY.Jrnlid,
GLENTRY.Amount,
GLENTRY.Dc,
GLENTRY.Ref,
GLENTRY.Refdt,
CONVERT(NVARCHAR(100),'Import of SS ' + CONVERT(VARCHAR(2),GLENTRY.Period) + '/' + CONVERT(VARCHAR(4),GLENTRY.Yearz) + ' GL activity') AS Descr,
GLENTRY.Invnr,
GLENTRY.Jrnllog,
ROW_NUMBER() OVER(PARTITION BY GLENTRY.Fac, GLENTRY.Yearz, GLENTRY.Period, GLENTRY.Pagez, GLENTRY.Acct, GLENTRY.Rundt, GLENTRY.Jrnlid,
GLENTRY.Amount, GLENTRY.Dc, GLENTRY.Ref, GLENTRY.Refdt, GLENTRY.Descr, GLENTRY.Invnr, GLENTRY.Origfac, GLENTRY.Jrnllog, GLENTRY.Seq
ORDER BY GLENTRY.Fac, GLENTRY.Yearz, GLENTRY.Period) AS m
FROM GLENTRY
LEFT OUTER JOIN
EntityTranslate2014 ON GLENTRY.Fac = EntityTranslate2014.Fac
LEFT OUTER JOIN
AcctTranslate2014 ON CONVERT(VARCHAR(8),GLENTRY.Acct) = AcctTranslate2014.SSAcct
WHERE GLENTRY.Yearz = 2014 AND GLENTRY.Period = 11
EntityTranslate2014 File
Fac Entity Descr AcctEnd SSDept Acct
1 51900 Entity1 0 0
2 50901 Entity2 0 0
3 10100 Entity3 0 0
3 10500 Entity4 4016 0
3 10500 Entity4 4020 0
3 10500 Entity4 4022 0
3 10500 Entity4 4024 0
3 10500 Entity4 4028 0
3 10500 Entity4 7016 0
4 30900 Entity5 0 0
5 10300 Entity6 0 0
6 11300 Entity7 0 0
7 11100 Entity8 0 0
7 11500 Entity9 4016 0
7 11500 Entity9 4020 0
7 11500 Entity9 4022 0
7 11500 Entity9 4024 0
7 11500 Entity9 4028 0
7 11500 Entity9 7016 0
9 32909 Entity10 0 0
10 12100 Entity11 0 0
11 32901 Entity12 0 0
12 53900 Entity13 0 0
13 10200 Entity14 0 0
14 32914 Entity15 0 0
15 32915 Entity16 0 0
16 11200 Entity17 0 0
17 32917 Entity18 0 0
18 32918 Entity19 0 0
19 32919 Entity20 0 0
20 32920 Entity21 0 0
21 13100 Entity22 0 0
22 52900 Entity23 0 0
89 99900 Entity24 0 0
123 12300 Entity25 0 0
124 12200 Entity26 0 0
133 13300 Entity27 0 0
201 11201 Entity28 0 0
202 11202 Entity29 0 0
402 25402 Entity30 0 0
403 25403 Entity31 0 0
549 25430 Entity32 0 0
549 25432 Entity33 7195 0
910 50910 Entity34 0 0
911 50911 Entity35 0 0
21 13500 Entity36 4016 0
21 13500 Entity36 4020 0
21 13500 Entity36 4022 0
21 13500 Entity36 4024 0
21 13500 Entity36 4028 0
21 13500 Entity36 7016 0
16 11202 Entity37 0 002 0
16 11201 Entity37 0 001 0
16 11200 Entity38 0 30918000
16 11200 Entity38 0 31918000
16 11200 Entity38 0 32110000
AcctTranslate2014
NewAcct SSAcct NewDEpt Fac
10111500 111200010 000 0
10111600 111200050 000 0
10111700 111550010 000 0
10113092 111050450 000 0
10115090 111050010 000 0
FROM GLENTRY
LEFT OUTER JOIN EntityTranslate2014
ON GLENTRY.Fac = EntityTranslate2014.Fac
LEFT OUTER JOIN AcctTranslate2014
ON CONVERT(VARCHAR(8), GLENTRY.Acct) = AcctTranslate2014.SSAcct
There's no relation defined between EntityTranslate2014 and AcctTranslate2014. If there's more than one record in either table for the corresponding record in GLENTRY, then those two tables will effectively cross-join with each other. For example, if a single GLENTRY joins to two records in EntityTranslate2014 and two records in AcctTranslate2014, then you'll get 4 records, one for each possible combination. That's simply how JOIN is defined.
If you know that this is happening and you know there's actually no relation, and you just want, say, for each record in GLENTRY the first record in EntityTranslate2014 to match to the first record in AcctTranslate2014, and the second record in EntityTranslate2014 to match to the second record in AcctTranslate2014 and so on, you can do what I've heard called a "ZIP JOIN":
FROM GLENTRY
LEFT OUTER JOIN (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY Fac ORDER BY <SomeField>) row_order
FROM EntityTranslate2014) ET2014
ON GLENTRY.Fac = ET2014.Fac
LEFT OUTER JOIN (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY SSAcct ORDER BY <SomeField>) row_order
FROM AcctTranslate2014) AT2014
ON CONVERT(VARCHAR(8), GLENTRY.Acct) = AT2014.SSAcct
AND AT2014.row_order = ET2014.row_order
Obviously, don't use SELECT *; this is just an example. So, what this is doing is assigning some order to each OUTER table, and them matching them up with each other. Thus, each record in each OUTER table will only show up once. If there's a mis-match, then the records from the other table will appear as NULLs.
The other common alternative is to simply return the first record for each OUTER table, so that you're guaranteed to only have one GLENTRY record since each OUTER table only contributes one or zero records for each key field.
If that doesn't work for your purposes, then you'll probably need to use two queries, and will need to do the matching in your application.
You can use a Correlated Subquery to "loop" through each row in one table comparing it to rows in another table without actually writing loop logic (which should be avoided in SQL). The rows in the inner query are compared to each row in the outer query based on the where predicate. Correlated Subqueries also allow you to filter the WHERE clause by the TOP 1 if more than 1 record would be returned in the WHERE clause query (as in the code below). This is just a brief example, as I don't have time to write out the code in its entirety, but it may help.
SELECT Entity
FROM EntityTranslate2014 ent
WHERE ent.AcctEnd <> ''
AND AcctEnd = (SELECT TOP 1 SUBSTRING(glt.Acct,6,3)
FROM Glentry glt
WHERE glt.fac = ent.fac
AND glt.Year = 2014
AND glt.Period = 11
ORDER BY glt.Fac, glt.Yearz, glt.Period)
In this example, each record from the EntityTranslate2014 table is compared to the results of the inner query based on the predicate that Glentry.Fac = EntityTraslate2014.fac. Hope that's helpful.
For more information on Correlated Subqueries, check out the following link.
https://technet.microsoft.com/en-us/library/ms187638%28v=sql.105%29.aspx
Updated...
You can use ROW_NUMBER to count sequences in the joined results, and ORDER BY to sort them so that the row you want is first in that sequence.
Thank you for posting the loop construct, I think I was able to approximate it's function with a series of CTEs(WITH alias as (...)). I'm not sure that I got all your table/field names correct, but this should be close to functional. A major guess on my part was how the "first" entity should be determined, you may need to tune the order by in the row number functions in the CTEs.
WITH ENTFIND AS (
SELECT
EntityTranslate2014.Fac,
EntityTranslate2014.Acct,
EntityTranslate2014.AcctEnd,
EntityTranslate2014.Entity,
EntityTranslate2014.SSDept,
EntityTranslate2014.Entity,
ROW_NUMBER() OVER (PARTITION BY Fac, Acct, AcctEnd ORDER BY Fac, Acct, AcctEnd, Entity) as E1Sort
FROM
EntityTranslate2014
),
E2 AS (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY Fac, Acct, AcctEnd ORDER BY Fac, Acct, AcctEnd, Entity) as E2Sort
FROM
ENTFIND
WHERE
AcctEnd <> 0
),
E3 AS (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY Fac, Acct, AcctEnd ORDER BY Fac, Acct, AcctEnd, Entity) as E3Sort
FROM
ENTFIND
WHERE
SSDept <> 0
),
E4 AS (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY Fac, Acct, AcctEnd ORDER BY Fac, Acct, AcctEnd, Entity) as E4Sort
FROM
ENTFIND
WHERE
Acct = 0
AND
AcctEnd = ''
AND
SSDept = 0
)
SELECT
GLENTRY.Fac + GLENTRY.Rundt + GLENTRY.Jrnllog AS UniqueID,
GLENTRY.Fac AS Fac,,
E1.Entity,
E2.Entity,
E3.Entity,
E4.Entity,
COALESCE(E1.Entity,E2.Entity,E3.Entity,E4.Entity) as 1stFoundEntity,
(CASE WHEN
EntityTranslate2014.AcctEnd <> '' AND EntityTranslate2014.AcctEnd = SUBSTRING(GLENTRY.Acct,6,3)
THEN
EntityTranslate2014.Entity
ELSE
CASE WHEN
EntityTranslate2014.AcctEnd <> 0 AND EntityTranslate2014.Acct = GLENTRY.Acct
THEN
EntityTranslate2014.Entity
ELSE
CASE WHEN
EntityTranslate2014.SSDept <> 0 AND EntityTranslate2014.SSDept = SUBSTRING(GLENTRY.Acct,1,4)
THEN
EntityTranslate2014.Entity
ELSE
CASE WHEN
EntityTranslate2014.SSDept = 0
AND
EntityTranslate2014.AcctEnd = ''
AND
EntityTranslate2014.Acct = 0
THEN
EntityTranslate2014.Entity
ELSE
''
END
END
END
END)
AS NEWEntity,
(CASE WHEN AcctTranslate2014.Fac = GLENTRY.Fac OR AcctTranslate2014.Fac = '0'
THEN
AcctTranslate2014.NEWDept
ELSE
Null
END)
AS Department,
(CONVERT(DATETIME,GLENTRY.Period + '/01/' +
CASE WHEN
CONVERT(NVARCHAR(4),GLENTRY.Yearz) = ''
THEN
'2014'
ELSE
GLENTRY.Yearz
END)
AS YEARPER,
GLENTRY.Acct) AS SSAcct,
CONVERT(NVARCHAR(20),
CASE WHEN
AcctTranslate2014.Fac = GLENTRY.Fac OR AcctTranslate2014.Fac = '0'
THEN
AcctTranslate2014.NEWAcct
ELSE
Null
END) AS NEWAccount,
GLENTRY.Rundt,
GLENTRY.Jrnlid,
GLENTRY.Amount,
GLENTRY.Dc,
GLENTRY.Ref,
GLENTRY.Refdt,
CONVERT(NVARCHAR(100),'Import of SS ' + CONVERT(VARCHAR(2),GLENTRY.Period) + '/' + CONVERT(VARCHAR(4),GLENTRY.Yearz) + ' GL activity') AS Descr,
GLENTRY.Invnr,
GLENTRY.Jrnllog,
ROW_NUMBER() OVER(PARTITION BY GLENTRY.Fac, GLENTRY.Yearz, GLENTRY.Period, GLENTRY.Pagez, GLENTRY.Acct, GLENTRY.Rundt, GLENTRY.Jrnlid,
GLENTRY.Amount, GLENTRY.Dc, GLENTRY.Ref, GLENTRY.Refdt, GLENTRY.Descr, GLENTRY.Invnr, GLENTRY.Origfac, GLENTRY.Jrnllog, GLENTRY.Seq
ORDER BY GLENTRY.Fac, GLENTRY.Yearz, GLENTRY.Period) AS m
FROM
GLENTRY
LEFT JOIN
ENTFIND E1 ON GLENTRY.Fac = E1.Fac
AND SUBSTRING(GLENTRY.Acct,6,3) = E1.AcctEnd
AND E1Sort = 1
LEFT JOIN
E2 ON GLENTRY.Fac = E2.Fac
AND GLENTRY.Acct = E2.Acct
AND E2.E2Sort = 1
LEFT JOIN
E3 ON GLENTRY.Fac = E3.Fac
AND SUBSTRING(GLENTRY.Acct,1,4) = E3.SSDept
AND E3.E3Sort = 1
LEFT JOIN
E4 ON GLENTRY.Fac = E4.Fac
AND E4.E4Sort = 1
LEFT OUTER JOIN
EntityTranslate2014 ON GLENTRY.Fac = EntityTranslate2014.Fac
LEFT OUTER JOIN
AcctTranslate2014 ON CONVERT(VARCHAR(8),GLENTRY.Acct) = AcctTranslate2014.SSAcct
WHERE
GLENTRY.Yearz = 2014 AND GLENTRY.Period = 11
I want to thank everyone for their ideas while I tried to get my query to work. I ended up with following solution. Note, for the sake of brevity, I only included the code for determining the Entity field. It's not pretty and I'm sure it's optimal, but it works.
Thanks again for all of your help!!
CASE WHEN
(SELECT
BET.Entity
FROM
BET
WHERE
GL.Fac = BET.Fac
AND
BET.AcctEnd <> ''
AND
BET.AcctEnd = SUBSTRING(CONVERT(NVARCHAR(8),GL.Acct),6,3))
IS NOT Null
THEN
(SELECT
BET.Entity
FROM
SOSViews.dbo.BI360EntityTranslate2014 BET
WHERE
GL.Fac = BET.Fac AND BET.AcctEnd <> ''
AND
BET.AcctEnd = SUBSTRING(CONVERT(NVARCHAR(8),GL.Acct),6,3))
ELSE
CASE WHEN
(SELECT
BET.Entity
FROM
SOSViews.dbo.BI360EntityTranslate2014 BET
WHERE
GL.Fac = BET.Fac
AND
BET.SOSDept <> 0
AND
BET.SOSDept = SUBSTRING(CONVERT(NVARCHAR(8),GL.Acct),1,4))
IS NOT Null
THEN
(SELECT
BET.Entity
FROM
BET
WHERE
GL.Fac = BET.Fac
AND
BET.SOSDept <> 0
AND
BET.SOSDept = SUBSTRING(CONVERT(NVARCHAR(8),GL.Acct),1,4))
ELSE
CASE WHEN
(SELECT
BET.Entity
FROM
BET
WHERE
GL.Fac = BET.Fac
AND
BET.SOSDept = 0 AND BET.AcctEnd = '' AND BET.Acct = 0)
IS NOT Null
THEN
(SELECT
BET.Entity
FROM
BET
WHERE
GL.Fac = BET.Fac
AND
BET.SOSDept = 0 AND BET.AcctEnd = '' AND BET.Acct = 0)
ELSE
'No Entity Translation'
END
END
END)
AS Entity,
Note: Although it may not be directly applicable to the OP's question, sometimes if there are too many rows in a join, it is as simple as joining on the wrong column. This just happened to me....

Resources