0

当我进行此选择时,结果显示所有“车辙”及其电话号码,我的问题是每个“车辙”有近 10 个电话号码,每个“车辙”只需要 3 个电话号码,我尝试使用 TOP,但只显示所有表的前 3 行,而不是“车辙”的第一行,我怎样才能将 TOP 仅用于“车辙”行,而不是在所有表中

Select Distinct  
t1.rut_cliente as rut_cliente,
t1.nro_fono  as numero 
--Into #tmp_numeros
From dat_clientes_sucursales_contactos_telefonos t1,dat_rut_clientes t2
where  t1.rut_cliente = t2.rut_cliente 
and cod_prioridad = 1

这就是我通过这个查询得到的:

  Rut_cliente   Nro_fono 
  60506000-5    2046840
  60506000-5    3507935
  60506000-5    4106886
  60506000-5    5440000
  60506000-5    5445000
  81698900-0    2373281
  81698900-0    3541342
  81698900-0    3541438
  81698900-0    3541518
  81698900-0    3542101

这就是我想要的:

  Rut_cliente   Nro_fono 
  60506000-5    2046840
  60506000-5    3507935
  60506000-5    4106886
  81698900-0    2373281
  81698900-0    3541342
  81698900-0    3541438

提前致谢。

4

3 回答 3

7

该问题最初标记为 SQL Server 2008,您可以在其中使用公用表表达式执行此操作:

;WITH x AS 
 (
   SELECT Rut_cliente, Nro_fono, rn = ROW_NUMBER()
     OVER (PARTITION BY Rut_cliente ORDER BY Nro_fono)
   FROM dbo.dat_clientes_sucursales_contactos_telefonos AS t1
   INNER JOIN dbo.dat_rut_clientes AS t2
   ON t1.rut_cliente = t2.rut_cliente
   WHERE cod_prioridad = 1
)
SELECT Rut_cliente, Nro_fono FROM x
WHERE rn <= 3
ORDER BY Rut_cliente, Nro_fono;

其他的建议:

  • 请不要使用table, table语法。使用正确INNER JOIN的 s。我在这里解释为什么
  • 请为内部查询添加适当的别名,以便人们知道哪些列来自 t1,哪些列来自 t2。

但是现在我们知道用户实际上在使用 SQL Server 2000。我想这就是我在那里的做法,但性能会很糟糕。我不是 100% 确定这有效(因为我再次猜测哪些列来自哪个表)。

SELECT x.rut_cliente, x.nro_fono, COUNT(*) FROM 
(
  SELECT t1.rut_cliente, t1.nro_fono
    FROM dat_clientes_sucursales_contactos_telefonos AS t1
    INNER JOIN dat_rut_clientes AS t2
    ON t1.rut_cliente = t2.rut_cliente
    WHERE cod_prioridad = 1
) AS x
INNER JOIN dat_clientes_sucursales_contactos_telefonos AS b
ON b.rut_cliente = x.rut_cliente
AND b.nro_fono <= x.nro_fono
GROUP BY x.rut_cliente, x.nro_fono
HAVING COUNT(*) <= 3
ORDER BY x.rut_cliente, x.Nro_fono;
于 2012-07-20T19:38:41.100 回答
5

例如 with which 是一个窗口函数,并返回由 . 确定的ROW_NUMBER每个分区(类似于 )的行号:group byorder by

WITH CTE AS(
   SELECT t1.rut_cliente as rut_cliente, t1.nro_fono  as numero,
      RN = ROW_NUMBER()OVER(PARTITION BY Rut_cliente ORDER BY Nro_fono)
   FROM dbo.dat_clientes_sucursales_contactos_telefonos AS t1
   INNER JOIN dbo.dat_rut_clientes AS t2 ON t1.rut_cliente = t2.rut_cliente
   WHERE cod_prioridad = 1
)
SELECT rut_cliente as rut_cliente, nro_fono  as numero
FROM CTE
WHERE RN <= 3
于 2012-07-20T19:38:53.830 回答
0

尝试这个

;with CTE AS (
select Rut_cliente, Nro_fono , ROW_NUMBER() OVER 
(PARTITION BY Rut_cliente ORDER BY Nro_fono) rn
 FROM dbo.dat_clientes_sucursales_contactos_telefonos AS a
INNER JOIN dbo.dat_rut_clientes AS b
ON a.rut_cliente = b.rut_cliente
WHERE cod_prioridad = 1

)
SELECT * FROM CTE where rn <=3
于 2012-07-20T19:39:58.420 回答