SQL Sub Query Needs to be modified to be more dynamic

I have a query that I need to reformat to account for the over 100 instances of a_AssignmentsIdName. This example shows only two possibilities(Full Swing and Media Fee) but there are many more.
Is there a way to reconstruct this query where I do not have to hardcode each and every instance of a_AssignmentsIdName.



  SELECT DISTINCT a_ActorID,
ap.a_ActorIdentifierName as Actor
,(select count(*) from a_partsandincrements as fs where fs.a_ActorIdentifierName=ap.a_ActorIdentifierName and fs.a_AssignmentsIdName='Full Swing'
) as [Full_Swing]
,(select count(*) from a_partsandincrements as mf where mf.a_ActorIdentifierName=ap.a_ActorIdentifierName and mf.a_AssignmentsIdName='Media Fee'
) as [Media Fee]
FROM a_partsandincrements ap
WHERE ap.a_ActorID IN ('143939','128473')

Open in new window


Output from query above
 a_ActorID	Actor	           Full_Swing	Media Fee
128473	                 Alv, Sandy	1	7
143939	                Arr, Andrew	5	6

Open in new window

swaggrKAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

PortletPaulEE Topic AdvisorCommented:
sorry... just realized what I proposed wasn't correct
0
PortletPaulEE Topic AdvisorCommented:
This is not the full solution, but it will simplify what you have been doing. Placing a case expression inside the COUNT() enables you to count with conditions.
SELECT
      ap.a_ActorID
    , ap.a_ActorIdentifierName as Actor
    , COUNT( case when fs.a_AssignmentsIdName='Full Swing' then ap.a_ActorID end ) as [Full Swing]
    , COUNT( case when fs.a_AssignmentsIdName='Media Fee' then ap.a_ActorID end ) as [Media Fee]
FROM a_partsandincrements AS ap
WHERE ap.a_ActorID IN ('143939', '128473')
GROUP BY
      ap.a_ActorID
    , ap.a_ActorIdentifierName
;

Open in new window


To make this  "more dynamic" requires using "dynamic SQL" which is SQL that actually writes new SQL and that new SQL is then executed. I may have time for that later, unless someone does it first.
0
Scott PletcherSenior DBACommented:
It's easy enough to see one total per row.  If you need to, we can instead dynamically pivot the data to columns, although that will be more overhead.

SELECT a_ActorID,
ap.a_ActorIdentifierName as Actor,
ap.AssignmentsIdName,
count(*) AS Count
FROM a_partsandincrements ap
WHERE ap.a_ActorID IN ('143939','128473')
GROUP BY a_ActorID, ap.AssignmentsIdName, ap.a_ActorIdentifierName
--ORDER BY Actor --,AssignmentsIdName
--ORDER BY AssignmentsIdName, Actor
0
10 Tips to Protect Your Business from Ransomware

Did you know that ransomware is the most widespread, destructive malware in the world today? It accounts for 39% of all security breaches, with ransomware gangsters projected to make $11.5B in profits from online extortion by 2019.

PortletPaulEE Topic AdvisorCommented:
Here is an approach to your "more dynamic" query.  It is the same logic as before; using case expressions inside the COUNT(); but now the SQL is generated.
DECLARE @cols  AS NVARCHAR(MAX)
DECLARE @query AS NVARCHAR(MAX)

SET @cols =   (SELECT DISTINCT 
                      ',' 
                     + ' COUNT( case when ap.a_AssignmentsIdName='
                     + ''''
                     + a_AssignmentsIdName 
                     + ''''
                     + ' then ap.a_ActorID end ) as '
                     + QUOTENAME(a_AssignmentsIdName) 
                   FROM a_partsandincrements
                   WHERE a_ActorID IN ('143939', '128473')
                   FOR XML PATH(''), TYPE
                  ).value('.', 'NVARCHAR(MAX)') 

set @query = 
    + ' SELECT ap.a_ActorID , ap.a_ActorIdentifierName as Actor'
    +     @cols
    + ' FROM a_partsandincrements AS ap'
    + ' WHERE ap.a_ActorID IN (''143939'', ''128473'')'
    + ' GROUP BY ap.a_ActorID , ap.a_ActorIdentifierName'


execute(@query)
;

Open in new window


To expand, you will need to alter the 2 where clauses

                   WHERE a_ActorID IN ('143939', '128473')

    + ' WHERE ap.a_ActorID IN (''143939'', ''128473'')'
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
swaggrKAuthor Commented:
@PortletPaul
thanks for the dynamic strategy but the the WHERE clause expansion part is giving me problems. How do I add a_ActorID without hardcoding over a thousand a_ActorID's?
0
PortletPaulEE Topic AdvisorCommented:
I was answring your soecific question:
        "reformat to account for the over 100 instances of a_AssignmentsIdName ..."

If you have a specific subset of id's to filter by, and that is the only viable method of filtering, then your options include:

1. insert those id's into a table (perhaps a temp table)
2. list those id's as a "union all" query
3. do 2 as a CTE
4. use 2 to do the insert for 1
5. use 3 to do the inserts for 1
6. hard code the query

I think that offering any more alternatives requires knowing both your data model and data.
0
swaggrKAuthor Commented:
@PortletPaul yes I understand. Are you able to assist or do I have to ASK another question?
0
PortletPaulEE Topic AdvisorCommented:
It may help you to get more folks on to a new question.

My point before though was I can give you technical options, but without familiarity with the data I can't offer much more than that.

Right now the only "simpler" way I can offer is to place the id's into a table (or equivalent)

SELECT id
into #my_id_list
FROM (
    SELECT 'abc' AS [id] UNION ALL
    SELECT 'edf' UNION ALL
    SELECT 'ghi' UNION ALL
    SELECT 'kjl' UNION ALL
    SELECT 'mno'
)

select
*
from some_table
where id in #my_id_list
;
0
swaggrKAuthor Commented:
@PortletPaul Thanks for all of your help. Trully appreciate it.
0
swaggrKAuthor Commented:
Extremely knowledgeable and helpful. Also, offered additional guidance on how to expand his suggestion.
0
PortletPaulEE Topic AdvisorCommented:
Thank you. Too kind.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.