小编Cra*_*g S的帖子

在 GROUP BY 和 COUNT 之后加入另一个表

我试图了解使用JOINCOUNT(*)GROUP BY进行非常简单的查询的正确方法。我实际上已经让它工作了(见下文),但从我读到的内容来看,我使用了GROUP BY不应该使用的额外内容。

(注意:下面的问题不是我的实际问题(它处理更复杂的表),但我试图提出一个类似的问题)

我有两张桌子:

Table: Person
-------------
key  name     cityKey
1    Alice    1
2    Bob      2
3    Charles  2
4    David    1

Table: City
-------------
key  name
1    Albany
2    Berkeley
3    Chico
Run Code Online (Sandbox Code Playgroud)

我想对WHERE返回的 People (带有一些子句)进行查询

  • 每个城市的匹配人数
  • 城市的钥匙
  • 城市的名称。

如果我做

SELECT COUNT(Person.key) AS count, City.key AS cityKey, City.name AS cityName
FROM Person 
LEFT JOIN City ON Person.cityKey = City.key 
GROUP BY Person.cityKey, City.name
Run Code Online (Sandbox Code Playgroud)

我得到了我想要的结果

count   cityKey   cityName
2       1 …
Run Code Online (Sandbox Code Playgroud)

sql group-by count aggregate-functions left-join

8
推荐指数
2
解决办法
6万
查看次数

是否有一种在SQL中生成任意线性序列的通用方法?

是否有我可以做的SQL查询将生成一个线性序列

1, 2, 3, 4, 5, 6, 7 ... x+1
Run Code Online (Sandbox Code Playgroud)

要么

2, 7, 12, 17, 22 ... 2+5x
Run Code Online (Sandbox Code Playgroud)

(其中每个数字是结果表的一行中的一个条目)

sql

5
推荐指数
1
解决办法
1215
查看次数

How can I use SQL to group and count the number of rows where the value for one column is <= x and the value for another column > x?

I'd like to group and count the number of entries in a table that meet criteria colA <= x < colB

Suppose I had the following table:

index  Game            MinAgeInclusive   MaxAgeExclusive
--------------------------------------------------------
1      Candy Land      3                 8
2      Checkers        5                 255
3      Chess           12                255
4      Sorry!          6                 12
5      Monopoly        10                30

(this isn't what I'm doing, but it abstracts away a lot of the other complications with my setup)

Suppose I wanted to get a table that told …

sql

5
推荐指数
1
解决办法
295
查看次数

标签 统计

sql ×3

aggregate-functions ×1

count ×1

group-by ×1

left-join ×1