我一直在努力找到一个解决办法,让每个条目都有一个重复计数。但是我尝试的每个查询都将所有条目分组为一行或一个计数是不正确的。
这是我的桌子没有计数:
------------------------------------------------------
| id | last_name | last_4_ssn | type | complete_date |
------------------------------------------------------
| 1 | TEST | 1234 | CC | NULL |
| 2 | TEST | 1234 | CC | NULL |
| 3 | TEST | 1234 | CC | 2016-09-11 |
| 4 | TEST | 1234 | CC | 2016-09-06 |
| 5 | TEST | 1234 | CC | NULL |
| 6 | TEST | 1234 | FE | 2016-08-30 |
| 7 | TEST | 1234 | FE | 2016-09-01 |
| 8 | TEST | 1234 | FE | 2016-09-02 |
------------------------------------------------------
我正在尝试使用一个非空的complete_date来检查'last_name','last_4_ssn'和'type'的计数。
我希望我的结果表看起来像这样:
--------------------------------------------------------------
| id | last_name | last_4_ssn | type | complete_date | count |
--------------------------------------------------------------
| 1 | TEST | 1234 | CC | NULL | 0 |
| 2 | TEST | 1234 | CC | NULL | 0 |
| 3 | TEST | 1234 | CC | 2016-09-11 | 2 |
| 4 | TEST | 1234 | CC | 2016-09-06 | 2 |
| 5 | TEST | 1234 | CC | NULL | 0 |
| 6 | TEST | 1234 | FE | 2016-08-30 | 3 |
| 7 | TEST | 1234 | FE | 2016-09-01 | 3 |
| 8 | TEST | 1234 | FE | 2016-09-02 | 3 |
--------------------------------------------------------------
注意有2个CC是否有完整日期,3个FE有完整日期?这是我想要的计数;其中last_name,last_4_ssn和type all相同,且其complete_dates为NOT NULL。
我正在尝试的当前SQL是(但不完全存在):
SELECT
clients.id,
clients.session_type,
clients.last_name,
clients.complete_date,
clients.last_4_ssn,
dups.the_count
FROM clients
LEFT JOIN (
SELECT id,
COUNT(*) AS the_count,
session_type,
last_4_ssn,
last_name,
complete_date
FROM `clients`
GROUP BY last_name, last_4_ssn, session_type
HAVING the_count > 1 AND complete_date IS NOT NULL ) AS dups
ON (dups.last_4_ssn = clients.last_4_ssn AND dups.last_name = clients.last_name AND dups.session_type = clients.session_type)
GROUP BY clients.id
任何想法都将不胜感激。谢谢你的时间!
答案 0 :(得分:2)
SELECT t1.*,
COALESECE(t2.count, 0) -- NULL dates should show a 0 count
FROM clients t1
LEFT JOIN
(
SELECT last_name,
last_4_ssn,
type,
SUM(CASE WHEN complete_date IS NOT NULL THEN 1 ELSE 0 END) AS `count`
FROM clients
GROUP BY last_name,
last_4_ssn,
type
) t2
ON t1.last_name = t2.last_name AND -- join on name, ssn, and type
t1.last_4_ssn = t2.last_4_ssn AND
t1.type = t2.type AND
t1.complete_date IS NOT NULL -- but only join the count if date not NULL
在这里演示: