How to make a query with group_concat in sql server/powerpivot - sql

I need help on my query. I am trying to concatenate DonorIntent so that each BudgetNbr has a one to one relationship with the DonorIntnet field. Currently I am exlcuding the BudgetNbrs with multiple DonorIntent (820655 and 820885)
The below hasn't worked for me so any help would be great!
SELECT
vwGEGiftEndowmentSummary.BudgetNbr
,vwGEGiftEndowmentSummary.BudgetName
,ODSBudgetIndexCurrent.OrgCode
,ODSBudgetIndexCurrent.BudgetStatus
,DonorIntent = STUFF((
SELECT ',' + vwGEGiftEndowmentSummary.DonorIntent
FROM vwGEGiftEndowmentSummary di
WHERE di.BudgetNbr = vwGEGiftEndowmentSummary.BudgetNbr
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM
vwGEGiftEndowmentSummary
INNER JOIN SOMOrgDeptGroups
ON vwGEGiftEndowmentSummary.Org_dept = SOMOrgDeptGroups.OrgDeptLevel
INNER JOIN ODSBudgetIndexCurrent
ON vwGEGiftEndowmentSummary.BudgetNbr = ODSBudgetIndexCurrent.BudgetNbr
WHERE
SOMOrgDeptGroups.ExtFundExpGroup = N'ADMIN'
AND ODSBudgetIndexCurrent.BudgetType IN (N'06', N'54')
AND vwGEGiftEndowmentSummary.BudgetNbr NOT IN (N'820655', N'820885')
GROUP BY
vwGEGiftEndowmentSummary.BudgetNbr
,vwGEGiftEndowmentSummary.BudgetName
,DonorIntent
,ODSBudgetIndexCurrent.OrgCode
,ODSBudgetIndexCurrent.BudgetStatus

Question resolved. I needed to remove GROUP BY DonorIntent and place into the subquery

Related

Can anyone help me with a GROUP BY issue?

I have this query:
SELECT
tc.dv_task,
tc.dv_ci_item,
STUFF((
SELECT ',' + lob.name
FROM u_cmdb_ci_line_of_business lob
where lob.sys_id = tc.ci_item
GROUP BY tc.dv_task
FOR XML PATH('') ), 1, 1, '') AS LOBs
FROM task_ci tc
INNER JOIN u_cmdb_ci_line_of_business lob on tc.ci_item = lob.sys_id
It returns the following error: Msg 164, Level 15, State 1, Line 8
Each GROUP BY expression must contain at least one column that is not an outer reference.
I'm using Microsoft SQL Server 2016 (SP2-GDR) (KB4505220) - 13.0.5101.9 (X64)
Here's what I'm trying to accomplish: I have two tables task_ci (tc) and u_cmdb_line_of_business (lob). The tables join by tc.ci_item = lob.sys_id. For each dv_task on the tc table, I want one line that lists, in a comma-separated field, the related ci_items from the lob table. That's why I'm trying to group by dv_task.
If I take out the group by, I get this:
tc.dv_task LOBs (Stuff field)
123456 lob.ci_item 1
123456 lob.ci_item 2
I want this:
dv_task LOBs (Stuff field)
123456 lob. ci_item 1, lob.ci_item 2
But when I add that group by, as an attempt to get things in one row, I get that error. Hope that makes sense.
Can anyone tell me what I'm doing wrong?
EDIT: 03/23
Okay, I got it, I just changed it up to substring like this
select
inc.number,
substring((select ', ' + lob.name from task_ci tc
join u_cmdb_ci_line_of_business lob on lob.sys_id = tc.ci_item
where inc.sys_id = tc.task
for XML PATH('')),2,1000) as lob_sysid
from incident inc
where inc.number = 'INC1157655'
I'm still not sure what I was doing wrong with the STUFF but I'll try it with the different table to see how it works.
Thanks for the help.
I don't think you need the JOIN in the outer query:
SELECT tc.dv_task, tc.dv_ci_item,
STUFF((SELECT ',' + lob.name
FROM u_cmdb_ci_line_of_business lob
WHERE lob.sys_id = tc.ci_item
FOR XML PATH('')
), 1, 1, '') AS LOBs
FROM task_ci tc;
Okay, I got it, I just changed it up to substring like this
select
inc.number,
substring((select ', ' + lob.name from task_ci tc
join u_cmdb_ci_line_of_business lob on lob.sys_id = tc.ci_item
where inc.sys_id = tc.task
for XML PATH('')),2,1000) as lob_sysid
from incident inc
where inc.number = 'INC1157655'
I'm still not sure what I was doing wrong with the STUFF but I'll try it with the different table to see how it works.
Thanks for the help.

SQL server Stuff on multiple columns

I want to concatenate the value of multiple columns for the same ID.
I managed to concatenate for the first column, but when trying the same syntax for the second I'm having an error "The multi-part identifier EnqAct.[ActionID] could not be bound."
Example_Data_Result
Here I managed to group several MachineName together, as seen in "Column1" but I can't manage to group both the MachineName and Description in their own column
My working Query :
SELECT Enq.[EnquiryID],
Enq.[CustomerName],
DetPrio.[Description],
Stuff((SELECT ', ' + Mach.[MachineName]
FROM [dbo].[Machine] Mach
INNER JOIN [dbo].[MachineEnquiry] MachEnq
ON Mach.[MachineID] = MachEnq.[MachineID]
WHERE Enq.[EnquiryID] = MachEnq.[EnquiryID]
FOR XML PATH('')), 1, 2, ''),
DetAct.[Description]
FROM [dbo].[Enquiry] Enq
INNER JOIN [dbo].[EnquiryAction] EnqAct
ON EnqAct.[EnquiryID] = Enq.[EnquiryID]
INNER JOIN [dbo].[DetailsAction] DetAct
ON DetAct.[ActionID] = EnqAct.[ActionID]
INNER JOIN [dbo].[DetailsPriority] DetPrio
ON DetPrio.[PriorityID] = Enq.[Priority]
GROUP BY Enq.[EnquiryID],
Enq.[CustomerName],
DetPrio.[Description],
DetAct.[Description]
My non working Query :
SELECT Enq.[EnquiryID],
Enq.[CustomerName],
DetPrio.[Description],
Stuff((SELECT ', ' + Mach.[MachineName]
FROM [dbo].[Machine] Mach
INNER JOIN [dbo].[MachineEnquiry] MachEnq
ON Mach.[MachineID] = MachEnq.[MachineID]
WHERE Enq.[EnquiryID] = MachEnq.[EnquiryID]
FOR XML PATH('')), 1, 2, ''),
Stuff((SELECT ', ' + DetAct.[Description]
FROM [dbo].[DetailsAction] DetAct
INNER JOIN [dbo].[EnquiryAction] EnqAct
ON EnqAct.[ActionID] = DetAtc.[ActionID]
WHERE Enq.[EnquiryID] = EnqAct.[EnquiryID]
FOR XML PATH('')), 1, 2, '')
FROM [dbo].[Enquiry] Enq
INNER JOIN [dbo].[DetailsPriority] DetPrio
ON DetPrio.[PriorityID] = Enq.[Priority]
GROUP BY Enq.[EnquiryID],
Enq.[CustomerName],
DetPrio.[Description]
Both work the same way, I have a table Enquiry which will have an EnquiryID.
then in my table EnquiryAction or MachineEnquiry I will have entitys with an EnquiryID and an Action/Machine ID
Then in my DetailsAction/Machine Table I will have the Action/Machine ID, and the string I want to get and concatenate.
Why am I having an error and is it possible to achieve what I'm trying to do ?

What Is Wrong With This FOR XML PATH

I can't seem to figure out why this won't work in MS SQL Server. It seems to not group the lines. Specifically I see:
1036 SC
1036 S1
1094 VO
1094 V1
1094 V2
When I expect to see:
1036 SC,S1
1094 VO,V1,V2
Can someone see something wrong with the syntax?
SELECT DISTINCT oa.acct_cd AS [Account],
STUFF((SELECT ',' + CASE WHEN o.trans_type like 'BUY%' then 'buy of ' else 'sell of ' end + s.ticker AS [text()]
FROM [dbo].[synCRtblTS_ORDER] o INNER JOIN [dbo].[synCRtblCSM_SECURITY] s
ON o.SEC_ID = s.SEC_ID
WHERE o.ORDER_ID = oa.ORDER_ID AND o.status IN ('OPEN','WORK','PENDING')
FOR XML PATH('')), 1, 1, '') [buy/sell]
FROM [dbo].[synCRtblTS_ORDER_ALLOC] oa INNER JOIN tblPortfolio p
ON oa.ACCT_CD = p.Account INNER JOIN tblInvestmentObjective io
ON io.Code = p.InvestmentObjective
WHERE p.AsOfDate = (SELECT AsOfDate FROM tblDateAsOf) and io.CashMgmtStrategy IN ('SC','VO')
GROUP BY oa.ORDER_ID, oa.acct_cd
order by 1
The Information you give is not enough... Within your STUFF you create (and concatenate) string which should contain "buy of" or "sell of". You are missing this information in your output.
It's guessing that your SC, S1, VO values are CashMgmtStrategy entries. You are not concatenating them...
Without deeper knowledge of your tables I cannot solve your problem, but here you'll find a working example of concatenation via FOR XML and STUFF
This code will list all table's names and their columns in a comma delimited list.
SELECT DISTINCT tbls.name AS TableName,
STUFF(
(
SELECT ', ' + cols.name
FROM sys.columns AS cols
WHERE cols.object_id = tbls.object_id
FOR XML PATH('')
), 1, 2, '') AS ColumnList
FROM sys.tables AS tbls

SQL Concatenation using XML Path - multiple rows with multiple table references

I am trying to use the XML Path to run SQL Concatenation but I am running into a bit of a problem. I have one table that is being used as a reference table for values I want to concatenate.I have 3 columns in the reference table (M.PROD, S.PROD, & REF NUMB).
M.PROD=====>S.PROD======>Ref Numb
1===========>_===========>981024583
2===========>_===========>981024719
3===========>A===========>981024605
3===========>B===========>981024669
4===========>A===========>981024688
4===========>B===========>981024706
4===========>C===========>981024723
5===========>_===========>981024742
6===========>_===========>981024742
I have the main tables where the m.prod and s.prod are used to match the reference table for Ref Numb values. What I want to do is concatenate the Ref Numb values based on what is being selected in main tables. The out put I am looking for is this:
M.Prod======>Ref Numb
1===========>981024583
2===========>981024719
3===========>981024605, 981024669
4===========>981024688, 981024706, 981024723
5===========>981024742
6===========>981024742
I am using the following query:
SELECT DISTINCT P.PRODUCT,
(STUFF((SELECT DISTINCT ',' + P1.REFNUMB AS [text()]
FROM PRODUCT P1
WHERE P1.PRODUCT = P.PRODUCT
FOR XML PATH('')), 1, 1, ''))
FROM PRODUCT P
This gives me the output of:
M.Prod======>Ref Numb
1===========>981024583
2===========>981024719
3===========>981024605, 981024669
4===========>981024688, 981024706, 981024723
5===========>981024742
6===========>981024742
However, there are times where all the s.prod are not in the main tables. So for this I use this query:
SELECT DISTINCT P.PRODUCT,
(STUFF((SELECT DISTINCT ',' + P1.REFNUMB AS [text()]
FROM PRODUCT P1
WHERE P1.PRODUCT = P.PRODUCT AND P1.SUBID = P.SUBID
FOR XML PATH('')), 1, 1, ''))
FROM PRODUCT P
This query produces following output for me:
M.Prod======>Ref Numb
1===========>NULL
2===========>NULL
3===========>981024605
3===========>981024669
4===========>981024688
4===========>981024723
5===========>NULL
6===========>NULL
The output I need in these cases is:
M.Prod======>Ref Numb
1===========>981024583
2===========>981024719
3===========>981024605, 981024669
4===========>981024688, 981024723
5===========>981024742
6===========>981024742
Any solution for this will be greatly appreciated, Thank you.
I'm not sure if I understood your question correctly, but try this:
SELECT DISTINCT P.PRODUCT,
(STUFF((SELECT DISTINCT ',' + P1.REFNUMB AS [text()]
FROM PRODUCT P1
WHERE P1.PRODUCT = P.PRODUCT
AND (P1.SUBID = P.SUBID OR P1.SUBID IS NULL AND P.SUBID IS NULL)
FOR XML PATH('')), 1, 1, ''))
FROM PRODUCT P

Parsing error when creating view

I have a view which takes multiple rows and Comma Separated Values (CSV) from table columns with data.
It was working well and I got the results that I needed. Now the view has some parsing error like:
Error in WHERE clause near '('. Unable to parse query text.
Can someone help? Here is my code:
SELECT dbo.table1.title,
Stuff((SELECT ', ' + CONVERT(NVARCHAR(4000), dbo.table3.uid) AS [text()]
FROM dbo.table2
INNER JOIN dbo.table3
ON dbo.table3.uid = dbo.table2.FK_Group
WHERE dbo.table3.uid = dbo.table2.FK_Group
AND dbo.table3.company = dbo.main.company
AND dbo.table2.FK_Version = dbo.table1.fk_Version
AND dbo.main_version.uid = dbo.table1.fk_Version
FOR XML PATH('')), 1, 1, '') AS groupName
FROM dbo.main_version
INNER JOIN dbo.[main]
ON dbo.version.fk_main = dbo.[main].uid
INNER JOIN dbo.main_schema
ON dbo.[main].fk_SCHEMA = dbo.main_schema.uid
INNER JOIN dbo.table1
ON dbo.version.uid = dbo.table1.fk_Version
WHERE ( dbo.main_version.active = 1 )