简体   繁体   中英

SQL Server Combining queries

I'm trying to get a user's total visits number for each web URL page that is stored in my database.
Bellow is my SQL query that will show total unique users where URL contains that keyword.

SELECT COUNT(DISTINCT userId) as someUrlTitleTotalVisitors
FROM someTable
WHERE urlCol LIKE '%someUrlKeyword%'

Now I have 50+ more pages to go, example:

SELECT COUNT(DISTINCT userId) as anotherUrlTitleTotalVisitors
FROM someTable
WHERE urlCol LIKE '%anotherUrlKeyword%'

.etc..

I would assume that I don't need to write 50+ separate queries for each URL title, and I should be able to get all data with one call.

So, my question is how can I combine this query as one?

Ok, if you don't have those keywords that you want to check on a table, then sadly, you are looking on a query like this:

SELECT  CASE WHEN urlCol LIKE '%Url-Title-1%' THEN 'Url-Title-1'
        WHEN urlCol LIKE '%Url-Title-2%' THEN 'Url-Title-2'
        WHEN urlCol LIKE '%Url-Title-3%' THEN 'Url-Title-3'
        WHEN urlCol LIKE '%Url-Title-4%' THEN 'Url-Title-4'
        ..... END Url,
        COUNT(DISTINCT userId)  TotalVisitors
FROM someTable
WHERE urlCol LIKE '%Url-Title-1%'
OR urlCol LIKE '%Url-Title-2%'
OR urlCol LIKE '%Url-Title-3%'
OR urlCol LIKE '%Url-Title-4%'
.....
GROUP BY CASE WHEN urlCol LIKE '%Url-Title-1%' THEN 'Url-Title-1'
         WHEN urlCol LIKE '%Url-Title-2%' THEN 'Url-Title-2'
         WHEN urlCol LIKE '%Url-Title-3%' THEN 'Url-Title-3'
         WHEN urlCol LIKE '%Url-Title-4%' THEN 'Url-Title-4'
         ..... END

Now, if you could put those keywords on a table, your query would be like this:

SELECT  B.KeyWord,
        COUNT(DISTINCT userId)  TotalVisitors
FROM someTable A
INNER JOIN TableWithKeywords B
ON A.urlCol LIKE '%' + B.KeyWord + '%'
GROUP BY B.KeyWord

quite a difference, right?, and you could add or remove keywords on that table without touching your query, very handy.

Sounds like you need to group by URL:

SELECT urlCol, COUNT(DISTINCT userId) as title1TotalVisitors
FROM someTable
GROUP BY urlCol
SELECT COUNT(DISTINCT userId) as title1TotalVisitors,urlCol 
FROM someTable
WHERE urlCol LIKE '%Url-Title-[1-50]%'
Group by urlCol 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM