gpt4 book ai didi

sql - 在GROUP BY c之后如何计算(DISTINCT a,b)

转载 作者:行者123 更新时间:2023-12-03 18:43:12 25 4
gpt4 key购买 nike

我有一个由三列组成的表:newspaperpersonpage
一个人可以多次阅读一个页面,这意味着我们可能会有一个这样的表:

newspaper   person  page
--------- ------ ----
NY Times A 1
NY Times A 1
NY Times A 1
NY Times A 2
NY Times B 8
NY Times B 9
NY Times B 9
WashPost A 1
WashPost B 1


我想为每份报纸(= COUNTGROUP BY newspaper,某人阅读一页的次数。为了弄清楚我的意思,对于上面的输入表,结果必须类似于:

newspaper     COUNT
--------- --------
NY Times 4 => (A,1) (A,2) (B,8) (B,9)
WashPost 2 => (A,1) (B,1)


我的第一次尝试是下面的查询, sqlite不允许这样做,但可以弄清楚我需要什么:

SELECT newspaper, COUNT(DISTINCT person, page)
FROM T
GROUP BY newspaper




作为一种解决方法,我可以使用 person连接 page||列,并且查询可以正常工作,但是我正在考虑一个更好的解决方案。

SELECT newspaper, COUNT(DISTINCT person || page)
FROM T
GROUP BY newspaper

最佳答案

您需要的是distinct消除重复,然后为每份报纸删除count(*)行。为此,我们使用子查询:

select newspaper, count(*) as reads_no
from (
select distinct newspaper, person, page
from t
) t
group by newspaper


您不应该连接两个字段并对其进行区分,因为除非与某些疯狂的定界符一起使用,否则您可能会丢弃一些值,除非您知道这些疯狂的定界符在字段中将永远不存在。请参见以下示例。

'aab' || 'xzy' = 'aa' || 'bxzy'

关于sql - 在GROUP BY c之后如何计算(DISTINCT a,b),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51078819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com