[英]mysql group and filter results
I have 2 queries! 我有2个查询!
select LINE, ACCOUNT
from DATAS
where date between "2015-07-01" and "2015-07-15"
and SIG="in"
group by ACCOUNT
order by ACCOUNT
and 和
select LINE, ACCOUNT
from DATAS
where date between "2015-07-01" and "2015-07-15"
and SIG="out"
group by ACCOUNT
order by ACCOUNT
Sample results: 样本结果:
LINE-ACCOUNT, SIG
0-1309 IN
0-1331 IN
0-1340 IN
0-1361 IN
0-1404 IN
0-1555 IN
LINE-ACCOUNT, SIG
0-1098 OUT
0-1309 OUT
0-1322 OUT
0-1331 OUT
0-1340 OUT
0-1555 OUT
I want 2 queries that will give that results: 我想要2个查询来给出结果:
I solved it in excel, but it is too complicated to solve it day by day! 我在excel中解决了它,但是要解决它太复杂了! ;)
;)
if it is easier I accept the solution in php too! 如果更容易,我也接受php中的解决方案!
I hope you understand what I want! 希望你理解我想要的!
thanks in advance 提前致谢
Have you tried something like this? 你尝试过这样的事情吗?
select * from
(
(select LINE, ACCOUNT, SIG
from DATAS
where date between "2015-07-01" and "2015-07-15"
and SIG="in"
group by ACCOUNT
order by ACCOUNT)
union all
(select LINE, ACCOUNT, SIG
from DATAS
where date between "2015-07-01" and "2015-07-15"
and SIG="out"
group by ACCOUNT
order by ACCOUNT)
) t1
group by LINE, ACCOUNT
having count(Line) = 1
EDIT:Corrected the query 编辑:更正了查询
EDIT: Here's a brief explanation on how the query works. 编辑:这是有关查询工作原理的简要说明。 First off, we select every line that has SIG = 'IN'... then we append every line that has SIG = 'OUT'.
首先,我们选择每条具有SIG ='IN'的行...然后添加每条具有SIG ='OUT'的行。
Now is where it gets interesting. 现在是有趣的地方。 If a line has both an IN and an OUT statement, it'll appear twice in our current resultset because it'll be part of both the SIG = "IN" and SIG = "OUT" query.
如果某行同时具有IN和OUT语句,它将在我们当前的结果集中出现两次,因为它既是SIG =“ IN”也是SIG =“ OUT”查询的一部分。 On the other hand, a line that only has an "IN" or an "OUT" will only appear in one of the two inner query.
另一方面,仅具有“ IN”或“ OUT”的行将仅出现在两个内部查询之一中。 We're going to take advantage of this.
我们将利用这一点。
The outer select statement with its "group by LINE, ACCOUNT" statement flattens our resultset and thus allows us to use the count() function. 带有“ group by LINE,ACCOUNT”语句的外部select语句使我们的结果集平坦化,从而使我们可以使用count()函数。 If a line appears in both queries, the count() will equal two... on the other hand, if a line appears only in one of the two queries, the count() will equal one.
如果在两个查询中都出现一行,则count()等于2 ...另一方面,如果仅在两个查询之一中出现一行,则count()等于1。 Those are the lines we want.
这些就是我们想要的线。
Still, in SQL, you can't do: 不过,在SQL中,您不能执行以下操作:
select * from table where count() > 1
If you want to place a condition using an aggregate function, you have to use the "having" clause, which is placed after a "group by" statement and acts exactly like a "where", only with an aggregate function. 如果要使用聚合函数放置条件,则必须使用“具有”子句,该子句仅在聚合函数的情况下放在“ group by”语句之后,并且其行为与“ where”完全相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.