我有一个包含67列和大约36,000行的表,我需要根据其中两列来运行SELECT。
重要的列是FINANCIAL_ACCOUNT_ID,EVENT_DESCRIPTION。
FINANCIAL_ACCOUNT_ID是每个帐户的唯一编号,但在表格中可能不是唯一的。事件描述不是唯一的。事件描述可以包含事件1' '活动2' '活动3'等等。
所以表格看起来像这样:
TABLE
+----------------------+-------------------+-------------+
| FINANCIAL_ACCOUNT_ID | EVENT_DESCRIPTION | OTHER_STUFF |
+----------------------+-------------------+-------------+
| 1121 | Event 1 | n/a |
| 107401 | Event 2 | n/a |
| 256483 | Event 1 | n/a |
| 1121 | Event 3 | n/a |
| 107401 | Event 1 | n/a |
| 363586 | Event 1 | n/a |
| 546875 | Event 1 | n/a |
| 546875 | Event 2 | n/a |
+----------------------+-------------------+-------------+
RESULT
+----------------------+-------------------+-------------+
| FINANCIAL_ACCOUNT_ID | EVENT_DESCRIPTION | OTHER_STUFF |
+----------------------+-------------------+-------------+
| 107401 | Event 2 | n/a |
| 107401 | Event 1 | n/a |
| 546875 | Event 1 | n/a |
| 546875 | Event 2 | n/a |
+----------------------+-------------------+-------------+
我需要返回的是整个行,如果有一个金融帐户ID,那么事件1'和'事件2'。
我已尝试将WITH子句与内部联接结合使用...在我最近的尝试中,我添加了一个计数(financial_account_id),例如:
select FINANCIAL_ACCOUNT_ID, EVENT_DESCRIPTION, COUNT(FINANCIAL_ACCOUNT_ID)
FROM master
group by FINANCIAL_ACCOUNT_ID
HAVING COUNT(FINANCIAL_ACCOUNT_ID) >1;
但是,以下是我在选择语句中看到的结果:
Financial_Account_ID | Event_Description | COUNT(Financial_Account_ID)
107401 | Event 2 | 2
546875 | Event 1 | 2
(我说我需要整行,但是一旦我得到了正确的结果,我就可以过滤掉我不需要的无关列。)
对这样的SQL查询应该是什么样的帮助? 详细信息:mariadb 10,databasename:JuneEvents,表名:master 我还在MS-SQL 2012 Express db中获得了副本
编辑:@Tim - 很抱歉,我需要将每个帐户与“事件1”相匹配。和'事件2'抛掷事件3和可能存在的任何其他事件。这澄清了吗?
解: 我使用了@ Gordon的第二个查询,将JOIN作为跳出点,最后得到了一个如下所示的最终查询:(注意:现在有一些额外的字段,但我在初始查询返回之后添加了它们propper得自初始数据集。)
SELECT t.financial_account_id, t.event_description, t.sold_quantity, t.paid_amount
FROM master t JOIN
(SELECT financial_account_id
FROM master t
WHERE event_description IN ('Event 1', 'Event 2')
GROUP BY financial_account_id
HAVING COUNT(DISTINCT event_description) = 2
) tt
ON tt.financial_account_id = t.financial_account_id
WHERE (event_description IN ('Event 1', 'Event 2') AND (sold_quantity > 0));
答案 0 :(得分:0)
以下查询将产生同时包含FINANCIAL_ACCOUNT_ID
和'Event 1'
且仅 这两个事件的所有'Event 2'
。如果您想提取其他信息,可以轻松地将此结果加入另一个表格。
SELECT FINANCIAL_ACCOUNT_ID,
SUM(CASE WHEN EVENT_DESCRIPTION IN ('Event 1', 'Event 2') THEN 1 ELSE 0 END) AS eventCount
FROM yourTable
GROUP BY FINANCIAL_ACCOUNT_ID
HAVING eventCount = 2 AND COUNT(*) = 2
答案 1 :(得分:0)
要获取两个事件的帐户,请使用:
SELECT financial_account_id
FROM master t
WHERE event_description IN ('Event 1', 'Event 2')
GROUP BY financial_account_id
HAVING COUNT(DISTINCT event_description) = 2;
然后要获取原始行,请使用JOIN
:
SELECT t.*
FROM master t JOIN
(SELECT financial_account_id
FROM master t
WHERE event_description IN ('Event 1', 'Event 2')
GROUP BY financial_account_id
HAVING COUNT(DISTINCT event_description) = 2
) tt
ON tt.financial_account_id = t.financial_account_id;