I have 2 tables called request and request relationship as detail below.
request
reqId regNum desc
12 111 Tomato
13 112 Carrot
14 113 Chilli
15 114 Onion
16 115 Garlic
requestRelationship
reqID relatedRequestId
12 14
12 16
13 14
13 15
What i would like to display like the following information
reqId regNum desc relateRequest
12 111 Tomato 113,115
13 112 Carrot 113,114
Currently i only have the basic query
select r.reqId, r.reqNum, r.desc, relateRequest = STUFF((select Distinct ', ' + regNum from request b where b.reqId = a.reqId FOR XML PATH (' ')), 1, 2, '')
from request r
INNER JOIN requestRelationship t WITH (NOLOCK) on r.reqID = t.reqID
order by r.reqId desc
Your STUFF essentially needs to join your request table on relatedrequestid (whereas your outer query is joining on reqID), so your whole select should look something like this:
SELECT DISTINCT R.reqID, R.regNum, R.[desc],
relateRequest = STUFF(
(SELECT DISTINCT ', ' + CAST(R2.regNum AS VARCHAR(10))
FROM request AS R2
JOIN requestRelationship AS RR2
ON RR2.relatedrequestid = R2.reqID
WHERE RR2.ReqID = RR.ReqID -- This joins to your outer query. -- You can also join on R.ReqID, doesn't make a difference.
FOR XML PATH ('')), 1, 2, '')
FROM request AS R
JOIN requestRelationship AS RR
ON RR.reqID = R.reqID;
Related
Should create a dynamic pivot table to report products sold monthly by company group.
There are several products and each company group might have a different combination of them.
The product status are Active and Cancelled.
The Active products are counted using the date where they were billed (dbilldate) and the cancelled should be counted using dtContractCancelledDate.
There are some cases where the company group does not sell or cancel a product during the month so all the column should reflect that (look on Prod2 Cancelled).
A calculation column should exist to calculate the net per product (Prod Active – Prod Cancelled).
We need help
• Creating different calculation to count the product active and cancelled using the corresponding dates (dbilled and dtcancelledbilled)
• Creating a column with 0s when there are not sold/cancelled products
• Creating the net columns for each product
• Creating the subtotals at the end of each column
This is the result desired:
Pd1Actv Pd1Cancd Pd1Net Prd2Actv Prd2Cancd Prd2Net Total
Comp1 6 5 1 15 0 15 16
Comp2 20 6 14 39 0 39 53
Comp3 63 14 49 82 0 82 131
Total 89 25 64 136 0 136 200
This is the main table from where data is extracted
SELECT [iCompId],[sContractStatusCode],[sContractStatusDesc],[dBillDate] ,dtContractCancelledBilled
FROM [Contract_Header]
This is what I have until now:
DECLARE
#cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX),
#Compgroupnumber as varchar(20),
#startdate as date,
#enddate as date
set #startdate=cast(DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) as
date)
set #enddate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
set #sCompGroupNumber ='DG10000174'
select #cols =
STUFF((SELECT distinct ',' + QUOTENAME(h.sProductCode+'
'+sContractStatusDesc)
from [Contract_Header] h
inner join [Comp_Header] d on d.iid=h.icompId
inner join [Comp_CompGroupLink] dgl on d.iId=dgl.CompId
inner join [Comp_DealerGroups] dg on dgl.iCompGroupId=dg.iId
where (h.sContractStatusCode='A' or h.sContractStatusCode='C') and
(h.dBillDate between #startdate and #enddate) and
sCompGroupNumber='DG10000174' and
h.sProductCode in
(
select distinct t.sProductCode
from [Contract_Header] t
inner join [Comp_Header] d on d.iid=t.iDealerId
inner join [Comp_CompGroupLink] dgl on d.iId=dgl.iCompId
inner join [Comp_CompGroups] dg on dgl.iDealerGroupId=dg.iId
where (t.sContractStatusCode='A' or t.sContractStatusCode='C') and
(t.dBillDate between #startdate and #enddate) and
sCompGroupNumber='DG10000174'
)FOR XML PATH('')) ,1,1,'')
set #query=
'SELECT sCompName,' + #cols + ' , +Total
from
(
select d.sCompName,
col = c.sProductCode+'' ''+c.sContractStatusDesc,c.sContractStatusCode,
from [Contract_Header] c
inner join [Comp_Header] d on d.iid=c.iDealerId
inner join [Comp_CompGroupLink] dgl on d.iId=dgl.iCompId
inner join [Comp_CompGroups] dg on dgl.iCompGroupId=dg.iId
where (dBillDate between '''+CAST(#startdate AS varchar)+''' and
'''+CAST(#enddate AS VARCHAR)+''') and
sCompGroupNumber='''+'DG10000174'+''' and
(c.sContractStatusCode='''+'A'+''' or
c.sContractStatusCode='''+'C'+''' ) and
sproductcode in
(select distinct sProductCode
from [Contract_Header] t
inner join [Comp_Header] d on d.iid=t.iCompId
inner join [Comp_CompGroupLink] dgl on d.iId=dgl.iCompId
inner join [Comp_CompGroups] dg on dgl.iCompGroupId=dg.iId
where (dBillDate between '''+CAST(#startdate AS varchar)+'''
and '''+CAST(#enddate AS VARCHAR)+''') and
(t.sContractStatusCode='''+'A'+''' or
t.sContractStatusCode='''+'C'+''' ) and
sCompGroupNumber='''+'DG10000174'+'''
)
) as DataSource
pivot
(
Count(sContractStatusCode)
for col in (' + #cols + ')
) p order by sCompName'
execute sp_executesql #query
This is the result of the query above
Pd1Actv Pd1Cancd Pd2Actv Pd3Actv
Comp 1 59 0 59 118
Comp 2 26 1 25 65
there are missing the columns when there are not products cancelled for Pd2 and Pd3, the net columns (pdAct-PdCanc), sub total and totals..
Thanks in advance for all the help...
mary
I have 2 tables in MS SQL Server.
Table 1
ID Name
-------------
10 Series
11 Movie
12 Music
13 Other
Table 2
ID IDCatg Value
---------------------------
1 10 Hannibal
2 10 Blacklist
3 10 POI
4 11 Hitman
5 11 SAW
6 11 Spider man
7 12 taylor swift
8 12 britney spears
I want to select by IDCatg in Table 2 and create a new column in Table 1 like this:
IDCatg Name Value
--------------------------------------------
10 Series Hannibal-Blacklist-POI
11 Movie Hitman-SAW-Spider man
12 Music taylor swift-britney spears
How can I do this by view?
You can do it using STUFF:
SELECT T21.IDCatg, T1.Name,
[Value] = STUFF((
SELECT '-' + T22.[Value]
FROM Table2 T22
WHERE T21.IDCatg = T22.IDCatg
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM Table2 T21 JOIN
Table1 T1 ON T1.ID=T21.IDCatg
GROUP BY T21.IDCatg,T1.Name
Result:
IDCatg Name Value
---------------------------------------------
10 Series Hannibal-Blacklist-POI
11 Movie Hitman-SAW-Spider man
12 Music taylor swift-britney spears
Sample result in SQL Fiddle
EDIT:
When the type of Value is int, you can cast it to varchar:
[Value] = STUFF((
SELECT '-' + CAST(T22.[Value] AS Varchar(MAX))
The query:
SELECT
(STUFF((SELECT ',' + CONVERT(VARCHAR(50),mode.model_name)
FROM InventoryMake SUB INNER JOIN Model mode ON SUB.model_ID = mode.model_ID
WHERE SUB.inv_ID = CAT.inv_ID FOR XML PATH('')), 1, 1, '' )) [Models],CAT.inv_ID
FROM Inventory CAT
Results from the query are as below:
Models inv_ID
Pulsar,Hunk 14
Splender,Hunk 15
Chaly (CF50),Hunk,CBZ,Splender 16
Pulsar,Hunk 17
Pulsar,Hunk,CBZ 18
As you can see from the query above InventoryMake table has the foreign keys from the tables Inventory and Model. Shown below are illustrations of those tables.
Inventory table
inv_ID inv_name
14 abc
15 bcx
16 glx
17 lco
18 btx
InventoryMake table
inm_id inv_ID model_ID
1 2 15
7 3 15
8 5 16
9 3 16
10 4 16
11 2 16
12 1 14
13 3 14
14 1 17
15 3 17
Model Table
model_ID model_name
1 Pulsar
2 Splender
3 Hunk
4 CBZ
5 Chaly (CF50)
What I need to do is to find the records for the users input that matches either inv_ID from the Inventory table or the model_name from the Model table. For that I have edited the query as below.
SELECT
(STUFF((SELECT ',' + CONVERT(VARCHAR(50),mode.model_name)
FROM InventoryMake SUB INNER JOIN Model mode ON SUB.model_ID = mode.model_ID
WHERE SUB.inv_ID = CAT.inv_ID FOR XML PATH('')), 1, 1, '' )) [Models],CAT.inv_ID
FROM Inventory CAT WHERE CAT.inv_ID LIKE '%#term%'
From the above query its possible to find the records that matches the term in inv_ID. But I need to find the records that matches either Inventory.inv_ID or Model.model_name. How do you suggest I can achieve this?
Thanks in advance.
PS: I'm using MSSQL
I don't knwo why your query has a function called STUFF neither what is FOR XML PATH('').
I'm also not sure about the meaning of '%#term%', or if it works as you seem to expect (it would not work in MySQL.
So, ignoring your query and looking at your formulated question, my answer is:
SELECT SUB.inm_id, SUB.inv_ID, SUB.model_ID
FROM InventoryMake SUB
INNER JOIN Inventory CAT ON (SUB.inv_ID = CAT.inv_ID)
INNER JOIN Model ON (SUB.model_ID = Model.model_ID)
WHERE CAT.inv_ID = #term
OR Model.model_name LIKE '%#term%'
Note that it does not make much sense to use LIKE against CAT.inv_ID. Maybe what you want is actually to match user's input against inv_name?
i have on sql server 2008 table like
EmployeeCertificationHistoryId EmployeeCertificationID EmployeeID CertificationID CertificationDate
1 244 2192 1 2/15/2006
2 185 2058 87 4/10/2010
3 245 2240 102 8/11/2013
4 246 2249 104 11/23/2005
5 247 2221 101 6/12/2013
6 248 2238 84 NULL
7 245 2240 102 8/11/2013
8 249 2240 102 8/4/2013
10 253 2175 84 6/19/2013
11 254 2239 105 2/5/2011
12 255 2239 111 11/22/2012
9 96 1468 92 12/6/2010
13 256 2239 110 11/22/2012
i need to comma seperate certificationid per employeeid.
for eg. for 2239=>105,111,110
i have written a query but it is giving all certificate id in one column. my query is
SELECT STUFF(
(SELECT ',' + CAST(C.CertificationID AS VARCHAR(100))
FROM tbl_PM_EmployeeCertificationMatrixHistory C
ORDER BY c.CertificationID
FOR XML PATH('')),1,1,'') AS CSV
GO
i just need employeeid and certificationid.but i am unable to sort it out.
You need a correlated subquery and a list of employees. The following gets the list of employees from the same table but you might have another table with this information:
SELECT e.EmployeeID,
STUFF((SELECT ',' + CAST(C.CertificationID AS VARCHAR(100))
FROM tbl_PM_EmployeeCertificationMatrixHistory C
where c.EmployeeID = e.EmployeeID
ORDER BY c.CertificationID
FOR XML PATH('')
),1, 1,'') AS CSV
from (select distinct EmployeeID
from tbl_PM_EmployeeCertificationMatrixHistory
) e;
You just need to add EmployeeID to the query as well as a WHERE and DISTINCT
SELECT DISTINCT A.EmployeeID, STUFF(
(SELECT ',' + CAST(C.CertificationID AS VARCHAR(100))
FROM tbl_PM_EmployeeCertificationMatrixHistory C
WHERE C.EmployeeID = A.EmployeeID
ORDER BY c.CertificationID
FOR XML PATH('')),1,1,'') AS CSV
FROM tbl_PM_EmployeeCertificationMatrixHistory A
GO
If you want to return only DISTINCT values in the the CSV list, add GROUP BY c.CertificationID above the ORDER BY
I have a table that contains some data given below. It uses a tree like structure
i.e.
Department
SubD1, SubD2 .....
PreSubD1, PreSubD1... PreSubD2, PreSubD2...
pk_map_id preferences ImmediateParent Department_Id
-------------------- -------------------- -------------------- --------------------
20 14 5 1
21 15 5 1
22 16 6 1
23 9 4 2
24 4 3 2
25 24 20 2
26 25 20 2
27 23 13 2
I want to group my records on behalf of department then immediate parent then preferences each separated by ','
i.e.
department Immediate Parent preferences
1 5,6 14,15,16
2 4,3,20,13 9,4,24,25,23
and this table also
Immediate parent preferences
5 14,15
6 16
4 9
3 4
20 24,25
13 13
In actual scenario all these are my ids which are to be replaced by their string fields.
I am using SQL server 2k5
You can use FOR XML PATH in a subquery to get the comma separated list of values. Then you GROUP BY your key field in order to get it for the right values.
For your first query
SELECT
[Department_Id],
STUFF(
(
SELECT
',' + CONVERT(varchar(10), [ImediateParent])
FROM
[YourTable] [YourTable2]
WHERE
[YourTable2].[Department_Id] = [YourTable].[Department_Id]
FOR XML PATH('')
), 1, 1, ''),
STUFF(
(
SELECT
',' + CONVERT(varchar(10), [Preferences])
FROM
[YourTable] [YourTable2]
WHERE
[YourTable2].[Department_Id] = [YourTable].[Department_Id]
FOR XML PATH('')
), 1, 1, '')
FROM
[YourTable]
GROUP BY
[YourTable].[Department_Id]
and for your second query
SELECT
[ImediateParent],
STUFF(
(
SELECT
',' + CONVERT(varchar(10), [Preferences])
FROM
[YourTable] [YourTable2]
WHERE
[YourTable2].[ImediateParent] = [YourTable].[ImediateParent]
FOR XML PATH('')
), 1, 1, '')
FROM
[YourTable]
GROUP BY
[YourTable].[ImediateParent]