例如我有
+------------+--------+-----------+
| PRIMARYKEY | NAME | TYPE |
+------------+--------+-----------+
| 0001 | Adam | Import |
| 0001 | Adam | Transfer |
| 0001 | Adam | Payment |
| 0002 | Brooke | Import |
| 0002 | Brooke | Transfer |
| 0003 | Chloe | Import |
| 0003 | Chloe | Transfer |
| 0003 | Chloe | Payment |
| 0004 | David | Import |
| 0004 | David | Transfer |
| 0005 | Emily | Import |
| 0005 | Emily | Transfer |
+------------+--------+-----------+
这是我的查询
SELECT
account.PRIMARYKEY,
client.NAME,
transaction.TYPE,
FROM
account
JOIN
client ON account.ACCOUNTKEY = client.PRIMARYKEY
JOIN
transaction ON account.PRIMARYKEY = transaction.ACCOUNTKEY
我想获取所有没有Payment
的数据并将其按PRIMARYKEY
分组
+------------+--------+-----------+
| PRIMARYKEY | NAME | TYPE |
+------------+--------+-----------+
| 0002 | Brooke | Import |
| 0004 | David | Import |
| 0005 | Emily | Import |
+------------+--------+-----------+
我试过
WHERE
transaction.TYPE NOT LIKE 'Payment'
但失败了
感谢您的帮助。
答案 0 :(得分:1)
您可以使用NOT EXISTS
。 WHERE
子句中的内部查询将获取所有已付款但仍使用NOT EXISTS
的帐户,它将排除内部查询中的所有帐户。
SELECT account.PRIMARYKEY,
client.NAME,
MIN(t.TYPE)
FROM account
JOIN client ON account.ACCOUNTKEY = client.PRIMARYKEY
JOIN transaction t ON account.PRIMARYKEY = t.ACCOUNTKEY
WHERE NOT EXISTS (
SELECT 1
FROM transaction a
WHERE a.ACCOUNTKEY = t.ACCOUNTKEY
AND a.Type = 'Payment'
)
GROUP account.PRIMARYKEY,
client.NAME
以下是一份指南,显示performance between IN, JOIN, EXISTS的差异。
答案 1 :(得分:1)
您可以使用SQL IN
statement:
SELECT
account.PRIMARYKEY,
client.NAME,
transaction.TYPE,
FROM
account
JOIN
client ON account.ACCOUNTKEY = client.PRIMARYKEY
JOIN
transaction ON account.PRIMARYKEY = transaction.ACCOUNTKEY
WHERE NOT account.PRIMARYKEY IN (SELECT ACCOUNTKEY FROM transaction WHERE TYPE = 'Payment'))
;
答案 2 :(得分:1)
这个怎么样:
SELECT PRIMARYKEY ,
NAME ,
TYPE
FROM YourTable
WHERE PRIMARYKEY NOT IN (SELECT PRIMARYKEY
FROM YourTable
WHERE TYPE = 'Payment'
)
AND TYPE = 'Import'
答案 3 :(得分:1)
这里的一种微创方法是加入一个额外的子查询,该子查询识别payment
永远不会作为类型出现的帐户。我们这是一个内连接,用于过滤掉我们不想要的非匹配帐户。
SELECT
a.PRIMARYKEY,
c.NAME,
t1.TYPE
FROM account a
INNER JOIN client c
ON a.ACCOUNTKEY = c.PRIMARYKEY
INNER JOIN transaction t1
ON a.PRIMARYKEY = t1.ACCOUNTKEY
INNER JOIN
(
SELECT ACCOUNTKEY
FROM transaction
GROUP BY ACCOUNTKEY
HAVING SUM(CASE WHEN TYPE = 'payment' THEN 1 ELSE 0 END) = 0
) t2
ON a.PRIMARYKEY = t2.ACCOUNTKEY;