创建未显示值的所有行的列表

时间:2018-05-30 14:28:22

标签: mysql sql

我有一个像这样的表(foo):

SELECT fk 
FROM foo
WHERE value <> 2;

我尝试创建一个列表,其中列出了未显示特定值的所有fk,例如值A, B, C

一次尝试就是这样做:

A

但是这仍然会返回2,因为B, C有两个条目,其中一个不是SELECT 'Core' as Core, Z.EventName, Sum(ISNULL(DIFF,0)) AS DIFF FROM (select distinct MacID, EventName from dbo.tblMachine a join (SELECT DISTINCT EVENTNAME FROM dbo.tblEvtDur) b on b.EventName <> '' and MacID in ('A06','A07', 'A08', 'A09', 'B01','B05','B09', 'B10', 'B11', 'C04', 'C08', 'C09') ) z LEFT JOIN (SELECT A.MacID, A.EventName, SUM(DATEDIFF(SECOND, A.STARTdt, A.eNDdt)) as diff,round(SUM(DATEDIFF(SECOND, A.STARTdt, A.eNDdt)) / cast(aVG(Tdiff) as decimal(30,8)),4) * 100 AS PER FROM dbo.tblEvtDur A LEFT JOIN ( SELECT macid, SUM(DATEDIFF(SECOND, STARTdt, eNDdt)) as Tdiff FROM dbo.tblEvtDur WHERE DayID between '20180401' and '20180430' GROUP BY MacID ) B ON A.MacID = B.MacID WHERE DayID between '20180401' and '20180430' AND A.MacID in ('A06','A07', 'A08', 'A09', 'B01','B05','B09', 'B10', 'B11', 'C04', 'C08', 'C09') group by A.MacID, A.EventName) a ON A.EVENTNAME = Z.EVENTNAME and Z.MacID = a.MacID order by Z.MacID, Z.EventName Group by Core, Eventname 。我需要{{1}}代替。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:4)

或者将GROUP BY与HAVING NOT和条件SUM结合使用

<强>查询

SELECT 
 foo.fk
FROM
 foo
GROUP BY
 foo.fk
HAVING 
 NOT SUM(foo.value = 2)

参见演示https://www.db-fiddle.com/f/kyP2ykqDEHTkM1E6NsdkEn/0

答案 1 :(得分:3)

使用not exists

select f.*
from foo f
where not exists (select 1 from foo f1 where f1.fk = f.fk and f1.value = 2);

答案 2 :(得分:2)

您可以找到与您的值映射的fk,然后消除它:

SELECT f.fk
FROM foo f
WHERE f.fk NOT IN (SELECT f1.fk FROM foo f1 WHERE f1.value = 2)