SQL select 个问题
SQL select problems
我有以下 table 名为 Find,我想 return 名称同时包含“/topic”和“/detail”的 SessionID 的数量。因此,在我的例子中它应该是 return 1,因为只有 SessionID=1 在 "name" 列中同时具有“/topic”和“/detail”。
我尝试使用以下代码,但我想我又搞砸了 GROUP BY。
谢谢!
Select count( distinct `SessionID`)
from Find
where `name` like "/detail%"
and `name` like "/topic%"
group by `SessionID`, `date`
order by `date`;
我还有一个名为 "date" 的列,它没有显示在我的屏幕截图中。日期列说明收集 SessionID 的日期。所以我想我可以出于上述目的按 SessionID 分组,然后按日期分组。所以最后我会知道每天满足要求的SessionID的个数。
您需要将查询分为两步。首先,您需要找出同时包含 /details%
和 /topic%
的会话。然后你可以数一数。
名称查找的数据透视行
SELECT
SessionID,
MAX(CASE WHEN name LIKE "/detail%" THEN 1 END) AS hasDetail,
MAX(CASE WHEN name LIKE "/topic%" THEN 1 END) AS hasTopic
FROM Find
GROUP BY SessionID
子查询结果为:
SessionID hasDetail hasTopic
--------- --------- --------
1 1 1
2 1
3 1
计算结果
SELECT COUNT(*)
FROM
(
SELECT
SessionID,
MAX(CASE WHEN `name` LIKE "/detail%" THEN 1 END) AS hasDetail,
MAX(CASE WHEN `name` LIKE "/topic%" THEN 1 END) AS hasTopic
FROM Find
GROUP BY SessionID
) AS A
WHERE A.hasDetail = 1 AND A.hasTopic = 1;
此查询是为 MySQL 数据库编写的,如果您需要其他 SQL 语句,例如 T-SQL for SQL Server,请告诉我。
您已经很接近了,您只需要将日期和计数作为不同的列包含在内。像这样:
Select `SessionID`, `date`, count(*) as number
from Find
where `name` like "/detail%"
or `name` like "/topic%"
group by `SessionID`, `date`
order by `date`;
我有以下 table 名为 Find,我想 return 名称同时包含“/topic”和“/detail”的 SessionID 的数量。因此,在我的例子中它应该是 return 1,因为只有 SessionID=1 在 "name" 列中同时具有“/topic”和“/detail”。
我尝试使用以下代码,但我想我又搞砸了 GROUP BY。
谢谢!
Select count( distinct `SessionID`)
from Find
where `name` like "/detail%"
and `name` like "/topic%"
group by `SessionID`, `date`
order by `date`;
我还有一个名为 "date" 的列,它没有显示在我的屏幕截图中。日期列说明收集 SessionID 的日期。所以我想我可以出于上述目的按 SessionID 分组,然后按日期分组。所以最后我会知道每天满足要求的SessionID的个数。
您需要将查询分为两步。首先,您需要找出同时包含 /details%
和 /topic%
的会话。然后你可以数一数。
名称查找的数据透视行
SELECT
SessionID,
MAX(CASE WHEN name LIKE "/detail%" THEN 1 END) AS hasDetail,
MAX(CASE WHEN name LIKE "/topic%" THEN 1 END) AS hasTopic
FROM Find
GROUP BY SessionID
子查询结果为:
SessionID hasDetail hasTopic
--------- --------- --------
1 1 1
2 1
3 1
计算结果
SELECT COUNT(*)
FROM
(
SELECT
SessionID,
MAX(CASE WHEN `name` LIKE "/detail%" THEN 1 END) AS hasDetail,
MAX(CASE WHEN `name` LIKE "/topic%" THEN 1 END) AS hasTopic
FROM Find
GROUP BY SessionID
) AS A
WHERE A.hasDetail = 1 AND A.hasTopic = 1;
此查询是为 MySQL 数据库编写的,如果您需要其他 SQL 语句,例如 T-SQL for SQL Server,请告诉我。
您已经很接近了,您只需要将日期和计数作为不同的列包含在内。像这样:
Select `SessionID`, `date`, count(*) as number
from Find
where `name` like "/detail%"
or `name` like "/topic%"
group by `SessionID`, `date`
order by `date`;