我确信之前已经回答过,但我找不到正确的条款来搜索我的答案。
我有一张表如:
USERNAME ACTIONNUM VALUE1 VALUE2
-------- ---------- ------ ------
Person1 Action1 0 1
Person1 Action1 1 1
Person1 Action1 1 1
Person1 Action2 0 1
Person1 Action2 1 1
Person2 Action3 0 1
Person2 Action3 1 1
Person3 Action4 1 1
对于这个例子,我想对VALUE1和VALUE2执行一次0,1的搜索,只给我USERNAME。所以第一次搜索会给出:Person1,Person2。
然后,第二次搜索应该给我一个不同的动作编号,并计算操作对于值1,1的次数,但只给我在第一次搜索中找到USERNAME的行。
因此,对于此示例,我希望查询返回:
USERNAME ACTIONNUM COUNT
-------- ---------- -----
Person1 Action1 2
Person1 Action2 1
Person2 Action3 1
因此跳过了Person3,因为Person3没有从第一次搜索返回
答案 0 :(得分:1)
您可以在子查询中使用IN:
select * from table where value1 = 1 and value2 = 1 and username in (
select username from table where value1 = 0 and value2 = 1
)
答案 1 :(得分:1)
改变这个答案,我误解了部分问题。
SELECT username, actionnum, (select count(actionnum)
from test1 b
where b.value1=1
and b.value2=1
and b.username = a.username
and b.actionnum = a.actionnum)
FROM test1 a
WHERE value1 = 0 AND value2 = 1
order by 1, 2;
请参阅sqlfiddle
答案 2 :(得分:1)
尝试这样的事情
Select
UserName
, ActionNum
, Count(*) As Cnt
From MyTable
Where Value1 = 1
And Value2 = 1
And UserName In
(
Select Distinct UserName
From MyTable
Where Value1 = 0
And Value2 = 1
)
Group By
UserName
, ActionNum
答案 3 :(得分:0)
你可以试试像..
SELECT
table.USERNAME,
table.ACTIONNUM,
COUNT(table.ACTIONNUM) as ACTIONNUMCOUNT
FROM
table
WHERE
table.VALUE1 = 1
AND
table.VALUE2 = 1
AND
USERNAME IN
(
SELECT DISTINCT USERNAME FROM table where value1 = 0 and value2 = 1
)
GROUP BY
table.ACTIONNUM