SQL Server组合查询

时间:2012-11-13 15:26:09

标签: sql sql-server

我正在尝试获取用户存储在我的数据库中的每个网址页面的总访问次数 Bellow是我的SQL查询,它将显示URL包含该关键字的唯一用户总数。

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

现在我还有50多页,例如:

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

.etc ..

我认为我不需要为每个网址标题编写50多个单独的查询,我应该能够通过一次调用获取所有数据。

所以,我的问题是如何将这个查询合并为一个?

3 个答案:

答案 0 :(得分:3)

好的,如果您没有要在桌面上查看的关键字,那么遗憾的是,您正在查看这样的查询:

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

现在,如果您可以将这些关键字放在表格上,那么您的查询将是这样的:

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

相当不同,对吗?你可以在不触及查询的情况下在该表上添加或删除关键字,非常方便。

答案 1 :(得分:1)

听起来您需要按网址分组:

SELECT urlCol, COUNT(DISTINCT userId) as title1TotalVisitors
FROM someTable
GROUP BY urlCol

答案 2 :(得分:-1)

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