0

我正在寻找一种更好的方法来生成仅使用 sql 而不是 C# 的列表。看起来很简单,我做错了

假设我有一个名为 PhoneNumbers 的表,其中包含 Number/City/State

示例(但数百万个数字):

NUMBER          CITY        STATE
555-555-5555    New York    NY
111-111-1111    Los Angeles CA
222-222-2222    Houston     TX
333-333-3333    Miami       FL

我需要一个从每个州返回 10 个电话号码的查询

现在我单独对所有 50 个状态运行查询,然后将它们组合到一个数据集中,但它是一个大数据库,所以它很慢,我希望有一个简单的方法来拉回我需要的数据。

4

3 回答 3

0

The below query should work for Oracle and SQL Server, but not for MySQL:

with cte as
(select number, city, state,
 row_number() over (partition by state order by state) rn
 from yourtable)

select number,city,state
from cte
where rn <= 10

Note that if you need the first 10 rows sorted by a particular field, you will have to tweak the order by to suit your needs.

于 2014-07-09T05:06:05.037 回答
0

it differs, but for MSSQL:

with cteByStateas (
   select row_number() over (partition by STATE order by CITY) as RowNo,
          number,
          city,
          state
)
select * 
  from cteByState
 where RowNo <= 10

Please note that you didnt specify which first 10 numbers you want, or if they should be random

for mysql, there it is done a bit different, using a variable

于 2014-07-09T05:07:58.693 回答
0

您可以简单地使用UNION ALL子句。像这样的东西: -

(SELECT NUMBER, CITY, STATE FROM TABLE_NAME WHERE STATE = 'NY' ORDER BY CITY LIMIT 10)
UNION ALL
(SELECT NUMBER, CITY, STATE FROM TABLE_NAME WHERE STATE = 'CA' ORDER BY CITY LIMIT 10)
UNION ALL
(SELECT NUMBER, CITY, STATE FROM TABLE_NAME WHERE STATE = 'TX' ORDER BY CITY LIMIT 10)
UNION ALL
(SELECT NUMBER, CITY, STATE FROM TABLE_NAME WHERE STATE = 'FL' ORDER BY CITY LIMIT 10)

希望这可以帮到你。

于 2014-07-09T05:12:12.490 回答