SQL 需要比较行计数值

SQL need to compare rows count values

我想查询 returns ID、名称和输入 ID 的次数 table。

SELECT 
    ID,
    NAME,
    COUNT(*) count
FROM 
    TABLE
GROUP BY
    NAME, ID, CASE_DETAIL_ID
HAVING
    COUNT(*) > 1;

本returns以下数据:

ID NAME COUNT
123 HAT 10
123 UMBRELLA 10
123 TOWEL 10
123 WATER 8
555 HAT 3
555 UMBRELLA 10
555 TOWEL 10
555 WATER 10
322 UMBRELLA 5
322 TOWEL 20
322 WATER 20

我希望能够查询计数小于具有相同 ID 的其他行的计数的行。我怎样才能做到这一点?这样最后的结果就是:

ID NAME COUNT FULL COUNT
123 WATER 8 10
555 HAT 3 10
322 UMBRELLA 5 20

我们存储了多个 ID,我只想要计数少于具有相同 ID 的行的 rows/names。

我也试过了-

WITH x AS
        (SELECT ID, NAME, COUNT(*) count
        FROM FRT.CASE_DETAIL_HISTORY
        GROUP BY
        NAME,
        ID,
        CASE_DETAIL_ID)
SELECT x.ID, t.NAME, X.COUNT, MIN(x.count)
FROM x
JOIN FRT.CASE_DETAIL_HISTORY t
on t.ID= x.ID
GROUP BY x.ID, t.ID, X.COUNT

但是,这并没有给我想要的东西。如果名称的计数与 ID 的 'mode' 计数不匹配,我只希望返回行。 我也尝试了以下但仍然面临错误:

WITH COUNT_OF_ROWS AS 
    (SELECT ID, NAME, COUNT(*) count
    FROM TABLE
    GROUP BY NAME, ID, CASE_DETAIL_ID
    HAVING COUNT(*) >= 1),
    
MINIMUM AS
    (SELECT COUNT_OF_ROWS.ID, COUNT_OF_ROWS.NAME, 
MIN(COUNT_OF_ROWS.COUNT) MINI
    FROM COUNT_OF_ROWS
    JOIN TABLE CD on CD.ID = COUNT_OF_ROWS.ID
    GROUP BY COUNT_OF_ROWS.ID, COUNT_OF_ROWS.NAME
)
     
select distinct COUNT_OF_ROWS.*, MINIMUM.MINI
from minimum, count_of_rows
where minimum.mini != count_of_rows.count;

一些示例数据会有所帮助,但您可以使用 CTE,并且 select 最低使用 min() 类似这样的东西:

WITH x AS(
    SELECT t.id, t.nametext, COUNT(*) as count
    FROM table t
    GROUP BY id, t.nametext, CASE_DETAIL_ID
), y as(
    SELECT x.id, MIN(x.[COUNT]) as mincount
    FROM x
    GROUP BY x.id
)
select y.id, x.nametext, y.mincount
from y
join x
on x.[COUNT] = y.mincount
and x.id = y.id

或者可以像这样使用 top 1order by 来完成:

SELECT TOP 1 id, name, COUNT(*) as count
FROM TABLE
WHERE ID = 123
GROUP BY NAME, ID, CASE_DETAIL_ID
ORDER BY count DESC

但是请记住,因为这只会 select 第一行,所以这只适用于 where 子句,因为它总是只有 return 1 行。

如果你使用 CTE 选项,如果你想要每个 id,它也可以工作,没有 where id = 123