UPDATE:
Finally, I got a fiddle together. I believe this makes it way more clear what I'm trying to achieve.
Please see http://sqlfiddle.com/#!18/fee65/1/0
My expected output is:
| Name | Count | SID |
| ------------ | ------------ | ------------ |
| VLAN115 | 3 | S-1 |
| VLAN116 | 2 | S-2 |
| VLAN118 | 4 | S-3 |
As you can see there're more VLAN's that 115, 116, 118. But I only need those three and count how many times the occur in COS_AD_memberOf.
Not sure about SIDs as they're unique so would be 3, 2, and 4 times the unique SID value in that column?
INITIAL POST
I have three names I want to check ('Name' column; more exist in the table) and I want to count the number of occurrences of them where they match part of the value of column 'COS_AD_memberOf'.
However, I'm only getting the same 'Count' for each of those three 'Name' column values.
SELECT COS_AD_name AS Name,
(
SELECT COUNT(*)
FROM CacheOrganizationStructure
WHERE COS_AD_memberOf LIKE '%VLAN115%'
OR COS_AD_memberOf LIKE '%VLAN116%'
OR COS_AD_memberOf LIKE '%VLAN118%') AS Count,
COS_SID AS SID
FROM CacheOrganizationStructure
WHERE COS_AD_name LIKE '%VLAN115%' OR COS_AD_name
LIKE '%VLAN116%' OR COS_AD_name
LIKE '%VLAN118%'
ORDER BY Name ASC
Name | Count | SID |
---|---|---|
VLAN115 | 166 | S-1 |
VLAN116 | 166 | S-2 |
VLAN118 | 166 | S-3 |
How can I amend the query so that it actually counts correctly?
2条答案
按热度按时间0dxa2lsx1#
You can use ROW_NUMBER to solve the problem
example:
expected
jv4diomz2#
You can use
PATINDEX
inside a subquery to calulcate the relevant value, then use a windowed count usingPARTITION BY
to get that.An alternative is to use a combination of
PATINDEX
andSUBSTRING
to pull the value out.You don't have to use windowing functions. A normal
GROUP BY
also works, and will aggregate up all the rows.SQL Fiddle