我有一张这样的表:
userid | trackid | path
123 70000 ad
123 NULL abc.com
123 NULL Apply
345 70001 Apply
345 70001 Apply
345 NULL Direct
345 NULL abc.com
345 NULL cdf.com
我想要这样的查询。当path ='abc.com'时,num_website +1;当path ='Apply'时,num_apply +1
userid | num_website | num_Apply | num_website/num_Apply
123 1 1 1
345 1 2 0.5
我的语法如下:
select * from
(select userid,count(path) as is_CWS
from TABLE
where path='abc.com'
group by userid
having count(path)>1) a1
JOIN
(select userid,count(userid) as Apply_num from
where trackid is not NULL
group by userid) a2
on a1.userid=a2.userid
我的问题是 1.如何根据上面的语法设置字段num_website / num_apply? 2.有没有其他更简单的方法来获得我想要的结果?
任何共享的景点都会欣赏。
答案 0 :(得分:0)
让你开始......你可以在此基础上构建:
select
userid,
SUM(CASE WHEN path='abc.com'then 1 else 0 end ) as num_website,
SUM(CASE WHEN path='Apply' and trackid is not NULL then 1 else 0 end ) as Apply_Num
from TABLE
WHERE path='abc.com' or path='Apply' -- may not need this ... play with it
group by userid
答案 1 :(得分:0)
最简单的方法是更改选择行:
static string Solve(List<object> source, string prefix = "")
{
int itemIndex = 0;
StringBuilder result = new StringBuilder();
foreach (object item in source)
{
List<object> listItem = item as List<object>;
if (listItem != null)
{
// If there was no preceding item, pretend there was one
if (itemIndex == 0)
{
itemIndex = 1;
}
result.Append(Solve(listItem, prefix + itemIndex + "."));
}
else
{
itemIndex++;
result.AppendLine(prefix + itemIndex + " " + item);
}
}
return result.ToString();
}
然后继续查询其余的查询。明星的意思是“选择一切”。如果你只想选择一些东西,你只需要列出那些东西代替星星,如果你想根据这些东西选择其他值,你也可以将它们放在星星中。在这种情况下, AttributeError: NoneType object has no attribute 'date1904'
是一个表达式,MySql知道如何根据a1.is_CWS和a2.Apply_num的值来评估它。
同样,您可以在单个表达式而不是子查询中执行许多子查询所执行的操作。 objectNotFound有正确的想法。您可以选择SELECT a1.userid, a1.is_CWS, a2.Apply_num, a1.is_CWS/a2.Apply_num FROM
(select userid,count(path) as is_CWS
from TABLE
where path='abc.com'
group by userid
having count(path)>1) a1
JOIN
(select userid,count(userid) as Apply_num
from TABLE
where trackid is not NULL
group by userid) a2
on a1.userid=a2.userid
而不必再加入子查询来检索具有特定属性的行数,而不必再加入。做出这样的改变给了我们:
a1.is_CWS/a2.Apply_num
注意我将GROUP BY移到了查询的末尾。另请注意,而不是引用a1.is_CWS我现在只引用is_CWS(它不再位于a1子表中,因此我们可以引用它)
您可以对其他子查询执行相同的操作,然后他们可以共享SUM(path="abc.com") as Apply_num
子句,您将不再需要连接。