Consider a database table connectouser holding two IDs:
connectouser
compID coopID
1 1
1 2
1 3
2 1
2 2
Consider another database table coop holding two IDs:
coop
ID Name
1 ABC
2 DEF
3 GHJ
I want to the following output :
Result
compID coopname
1 ABC,DEF,GHJ
2 ABC,DEF
Can anyone please help me on this.
The question was tagged MySQL for this answer.
This is a group by and group_concat():
select cu.compId, group_concat(co.name order by co.id) as coopnames
from connectouser cu join
coop co
on cu.coopID = co.ID
group by cu.compId;
In SQL Server, you can do:
select cu.compId,
stuff( (select ',' + co.name
from coop co
where cu.coopID = co.ID
order by co.id
for xml path ('')
), 1, 1, ''
) as names
from connectouser cu;
The most recent version of SQL Server supports string_agg(), which is a much better approach.
Related
I am trying to combine multiple rows into a single row that involves a JOIN. I cannot figure how to get the JOIN piece to work.
I am on SQL Server 2014.
This piece works great where I am rolling rows into a single comma separated line based on ID_REVIEW:
SELECT DISTINCT
ID_REVIEW
, STUFF((
SELECT N', ' + CAST(AREA_ID AS VARCHAR(255))
FROM AREA_ASSOC t2
WHERE t1.ID_REVIEW = t2.ID
FOR XML PATH('')
), 1, 1, '') AS AREA_ID
FROM REQUEST_WORKLOAD t1
Result:
ID_REVIEW | AREA_ID
-----------------
11438 | 2
23501 | 10, 15
44677 | 8
What I'd like to do is instead of having numbers for AREA_ID is have the name of that area show up. The goal being to have:
ID_REVIEW | AREA_NM
-----------------
11438 | State St.
23501 | Main St., Second St.
44677 | Adams Ave.
This AREA_NM information is contained in another table, called AREA. In a separate query, I can do a LEFT JOIN on table AREA_ASSOC to pull in the AREA_NM:
SELECT DISTINCT
[AREA_NM]
FROM AREA_ASSOC
LEFT JOIN AREA ON
AREA_ASSOC.AREA_ID = AREA.AREA_ID
I'm stumped as to how to get that JOIN into the STUFF function so I can get the area names. Is there a way to do this?
Do the join in the subquery:
SELECT DISTINCT r2.ID_REVIEW,
STUFF( (SELECT N', ' + a2AREA_NM
FROM AREA_ASSOC aa2 JOIN
AREA a
ON aa2.AREA_ID = A.AREA_ID
WHERE aa2.ID_REVIEW = r2.ID
FOR XML PATH('')
), 1, 2, ''
) AS AREA_ID
FROM REQUEST_WORKLOAD rw
I have a table in SQL Server 2008 R2 like this:
Acc_id Bench-1 Bench-2
-------------------------------
1 xx
1 vv
2 pp
2 ii
3 kk
4 ll
Now, I want to combine this table on the basis of Acc_id column and get something like:
Acc_id Bench-1 Bench-2
---------------------------------
1 xx vv
2 pp ii
3 kk
4 ll
So, could someone please help me out.
SELECT ISNULL(b1.Acc_id,b2.Acc_id) as Acc_id,
b1.data,
b2.data
FROM Bench-1 AS b1 FULL OUTER JOIN
Bench-2 AS b2 ON b2.Acc_id = b1.Acc_id
Check Below query
SELECT DISTINCT a.acc_id,
b.bench_1,
c.bench_2
FROM table1 a
LEFT OUTER JOIN (SELECT acc_id,
bench_1
FROM table1
WHERE Isnull(bench_1, '') <> '') b
ON a.acc_id = b.acc_id
LEFT OUTER JOIN (SELECT acc_id,
bench_2
FROM table1
WHERE Isnull(bench_2, '') <> '') c
ON a.acc_id = c.acc_id
I would do this like:
select
Acc_id,
max([Bench-1)] as [Bench-1],
max(([Bench-2]) as [Bench-2]
from
myTable
group by
Acc_id
This assumes Acc_id won't have multiple rows with data in the same columns
If that is the case then your knowledge of the use of the results will come into play. I often will perform this more completely like
select
Acc_id,
min([Bench-1)] as [Bench-1Min],
max([Bench-1)] as [Bench-1Max],
Count([Bench-1)] as [Bench-1Count],
min([Bench-2)] as [Bench-2Min],
max([Bench-2)] as [Bench-2Max],
Count([Bench-2)] as [Bench-2Count],
from
myTable
group by
Acc_id
All this depends on the actual complexity of the real data and what you want to do with the results. If it IS actually as simple as you example the multi-join solution may work for you, but I often find that in more complex summarizations the group by solution give me results and performance I need.
I have a couple of tables. One table with Groups:
[ID] - [ParentGroupID]
1 - NULL
2 1
3 1
4 2
And another with settings
[Setting] - [GroupId] - [Value]
Title 1 Hello
Title 2 World
Now I'd like to get "Hello" back if I'd query the Title for Group 3
And I'd like to get "World" back if I'd query the Title for Group 4 (And not "Hello" as well)
Is there any way to efficiently do this in MSSQL? At the moment I am resolving this recursively in code. But I was hoping that SQL could solve this problem for me.
Don't knoww the SQL Server syntax but something like the following?
SELECT settings.value
FROM settings
JOIN groups ON settings.groupid = groups.parentgroupid
WHERE settings.setting = 'Title'
AND groups.id = 3
This is a problem we've encountered multiple times in our company. This would work for any case, including when the settings can be set only at some levels and not others (see SQL Fiddle http://sqlfiddle.com/#!3/16af0/1/0 :
With GroupSettings(group_id, parent_group_id, value, current_level)
As
(
Select g.id as group_id, g.parent_id, s.value, 0 As current_Level
From Groups As g
Join Settings As s On s.group_id = g.id
Where g.parent_id Is Null
Union All
Select g.id, g.parent_id, Coalesce((Select value From Settings s Where s.group_id=g.id), gs.value), current_level+1
From GroupSettings as gs
Join Groups As g On g.parent_id = gs.group_id
)
Select *
From GroupSettings
Where group_id=4
I believe the following is what you are seeking. See the sqlfiddle
SELECT vALUE FROM
Groups g inner join Settings s
ON g.ParentGroupId = s.GroupID
WHERE g.ID = 3 -- will return Hello,], set ID = 4 will return World
How do I only select the stores that don't have client 5?
StoreId ClientId
------- ---------
1 4
1 5
2 5
2 6
2 7
3 8
I'm trying something like this:
SELECT SC.StoreId FROM StoreClients
INNER JOIN StoreClients SC
ON StoreClients.StoreId = SC.StoreId
WHERE SC.ClientId = 5
GROUP BY StoreClients.StoreId
That seems to get me all the stores that have that client but I can't do the opposite because if I do <> 5 ill still get Store 1 and 2 which I don't want.
I'm basically trying to use this result in another query's EXISTS IN clause
One way:
SELECT DISTINCT sc.StoreId
FROM StoreClients sc
WHERE NOT EXISTS(
SELECT * FROM StoreClients sc2
WHERE sc2.StoreId = sc.StoreId AND sc2.ClientId = 5)
SELECT SC.StoreId
FROM StoreClients SC
WHERE SC.StoreId NOT IN (SELECT StoreId FROM StoreClients WHERE ClientId = 5)
In this way neither JOIN nor GROUP BY is necessary.
SELECT DISTINCT a.StoreID
FROM tableName a
LEFT JOIN tableName b
ON a.StoreID = b.StoreID AND b.ClientID = 5
WHERE b.StoreID IS NULL
SQLFiddle Demo
OUTPUT
╔═════════╗
║ STOREID ║
╠═════════╣
║ 3 ║
╚═════════╝
SELECT StoreId
FROM StoreClients
WHERE StoreId NOT IN (
SELECT StoreId
FROM StoreClients
Where ClientId=5
)
SQL Fiddle
You can use EXCEPT syntax, for example:
SELECT var FROM table1
EXCEPT
SELECT var FROM table2
<> will surely give you all values not equal to 5.
If you have more than one record in table it will give you all except 5.
If on the other hand you have only one, you will get surely one.
Give the table schema so that one can help you properly
this is my sql problem - there are 3 tables:
Names Lists ListHasNames
Id Name Id Desc ListsId NamesId
=-------- ------------ ----------------
1 Paul 1 Football 1 1
2 Joe 2 Basketball 1 2
3 Jenny 3 Ping Pong 2 1
4 Tina 4 Breakfast Club 2 3
5 Midnight Club 3 2
3 3
4 1
4 2
4 3
5 1
5 2
5 3
5 4
Which means that Paul (Id=1) and Joe (Id=2) are in the Football team (Lists.Id=1), Paul and Jenny in the Basketball team, etc...
Now I need a SQL statement which returns the Lists.Id of a specific Name combination:
In which lists are Paul, Joe and Jenny the only members of that list ? Answer only Lists.Id=4 (Breakfast Club) - but not 5 (Midnight Club) because Tina is in that list, too.
I've tried it with INNER JOINS and SUB QUERIES:
SELECT Q1.Lists_id FROM
(
SELECT Lists_Id FROM
names as T1,
listhasnames as T2
WHERE
(T1.Name='Paul') and
(T1.Id=T2.Names_ID) and
( (
SELECT count(*) FROM
listhasnames as Z1
where (Z1.lists_id = T2.lists_Id)
) = 3)
) AS Q1
INNER JOIN (
SELECT Lists_Id FROM
names as T1,
listhasnames as T2
WHERE
(T1.Name='Joe') and
(T1.Id=T2.Names_ID) and
(
(SELECT count(*) FROM
listhasnames as Z1
WHERE (Z1.Lists_id = T2.lists_id)
) = 3)
) AS Q2
ON (Q1.Lists_id=Q2.Lists_id)
INNER JOIN (
SELECT Lists_Id FROM
names as T1,
listhasnames as T2
WHERE
(T1.Name='Jenny') and
(T1.Id=T2.Names_ID) and
(
(SELECT count(*) FROM
listhasnames as Z1
WHERE (Z1.Lists_id = T2.lists_id)
) = 3)
) AS Q3
ON (Q1.Lists_id=Q3.Lists_id)
Looks a little bit complicated, uh? How to optimize that?
I need only that Lists.Id in which specific names are in (and only these names and nobody else). Maybe with SELECT IN?
Regards,
Dennis
SELECT ListsId
FROM ListHasNames a
WHERE NamesId in (1, 2, 3)
AND NOT EXISTS
(SELECT * from ListHasNames b
WHERE b.ListsId = a.ListsId
AND b.NamesId not in (1, 2, 3))
GROUP BY ListsId
HAVING COUNT(*) = 3;
Edit: Corrected thanks to Chris Gow's comment; the subselect is necessary to exclude lists that have other people on them.
Edit 2 Corrected the table name thanks to Dennis' comment
Using Carl Manaster's solution as a starting point I came up with:
SELECT listsid
FROM listhasnames
GROUP BY listsid HAVING COUNT(*) = 3
INTERSECT
SELECT x.listsid
FROM listhasnames x, names n
WHERE n.name IN('Paul', 'Joe', 'Jenny')
AND n.id = x.namesid
Updated:
select a.ListsId from
(
--lists with three names only
select lhn.ListsId, count(*) as count
from ListHasNames lhn
inner join Names n on lhn.NamesId = n.Id
group by lhn.ListsId
having count(*) = 3
) a
where a.ListsId in (select ListsId from ListHasNames lhn where NamesId = (select NamesId from names where Name = 'Paul'))
and a.ListsId in (select ListsId from ListHasNames lhn where NamesId = (select NamesId from names where Name = 'Joe'))
and a.ListsId in (select ListsId from ListHasNames lhn where NamesId = (select NamesId from names where Name = 'Jenny'))
I was just solving a problem recently that may work well for your case as well. It may be overkill.
I took the approach of creating a list of candidate associations that may be the correct solution, and then using a cursor or queue table to go through the likely correct solutions to do full validation.
In my case this was implemented by doing like
select
ParentId
count(*) as ChildCount
checksum_agg(checksum(child.*) as ChildAggCrc
from parent join child on parent.parentId = child.parentId
Then you can compare the count and aggregate checksum against your lookup data (i.e. your 3 names to check for). If no rows match, you are guaranteed to have no matches. If any row matches you can then go through and do a join of that specific ParentId to validate if there are any discrepancies between the row sets.
Clear as mud? :)