我有以下查询:
SELECT DISTINCT TOP 20
f.id_service as f_id_service,
f.id_city as f_id_city,
f.name as f_name,
f.address as f_address,
f.business as f_business,
f.web as f_web,
f.phone as f_phone,
f.id_firm as f_id_firm
FROM
Firm f
left join
Price p ON p.id_service = f.id_service
AND p.id_city = f.id_city
AND p.id_firm = f.id_firm
WHERE
f.blocked = '0'
AND (f.name LIKE 'авто%'
OR f.phone LIKE 'авто%')
AND (f.phone != '' OR f.address != '')
AND f.id_city = '73041'
AND f.dogovor = '1'
ORDER BY f.name ASC
此查询显示前20行,其中包含唯一f.name
当我需要选择具有唯一f.name的下一行20行时,我使用下一个查询:
SELECT DISTINCT TOP 20
f.id_service AS f_id_service,
f.id_city AS f_id_city,
f.name AS f_name,
f.address AS f_address,
f.business AS f_business,
f.web AS f_web,
f.phone AS f_phone,
f.id_firm AS f_id_firm
FROM
Firm f
LEFT JOIN
Price p ON p.id_service = f.id_service
AND p.id_city = f.id_city
AND p.id_firm = f.id_firm
WHERE
f.name NOT IN (SELECT DISTINCT TOP 20
f.name
FROM
Firm f
WHERE
f.blocked = '0'
AND (f.name LIKE '????%'
OR f.phone LIKE '????%')
AND (f.phone != '' OR f.address != '')
AND f.id_city = '73041'
ORDER BY f.name ASC)
AND f.dogovor = '1'
AND f.blocked = '0'
AND (f.name LIKE '????%'
OR f.phone LIKE '????%')
AND (f.phone != '' OR f.address != '')
AND f.id_city = '73041'
AND f.dogovor = '1'
ORDER BY f.name ASC
但是我看到在最后一个查询中我查询从第一个查询中选择具有唯一f.name的行。
例如:
结果第一个查询(选择前20行):
结果第二个查询(选择NEXT TOP 20行):
如何在第二个图像中看到第二个查询具有第一个图像中的行(结果第一个查询)。
请告诉我哪里有错误,怎么写对了?
答案 0 :(得分:1)
试试这个 -
SELECT DISTINCT TOP 20
f.id_service AS f_id_service,
f.id_city AS f_id_city,
f.name AS f_name,
f.[address] AS f_address,
f.business AS f_business,
f.web AS f_web,
f.phone AS f_phone,
f.id_firm AS f_id_firm
FROM dbo.Firm f
WHERE f.blocked = '0'
AND (f.name LIKE 'авто%' OR f.phone LIKE 'авто%')
AND f.phone + f.[address] != ''
AND f.id_city='73041'
AND f.dogovor='1'
ORDER BY f.name
SELECT *
FROM (
SELECT DISTINCT
f.id_service AS f_id_service,
f.id_city AS f_id_city,
f.name AS f_name,
f.[address] AS f_address,
f.business AS f_business,
f.web AS f_web,
f.phone AS f_phone,
f.id_firm AS f_id_firm,
row_id = ROW_NUMBER() OVER (ORDER BY f.name)
FROM dbo.Firm f
WHERE f.blocked = '0'
AND (f.name LIKE 'авто%' OR f.phone LIKE 'авто%')
AND f.phone + f.[address] != ''
AND f.id_city='73041'
AND f.dogovor='1'
) d
WHERE d.row_id BETWEEN 21 AND 40
答案 1 :(得分:0)
当您选择表格的ID时,您可以不使用“Distinct”,这样您就可以按ID过滤掉前20个记录。
WHERE f.id_service NOT IN( SELECT TOP 20 f.id_service FROM Firm f WHERE f.blocked ='0'...
答案 2 :(得分:0)
首先,它可能是一个语言障碍但是很明显,你的第一个查询不会显示唯一的f.name,而是显示所有列的唯一组合。
此外,以这种方式使用TOP和DISTINCT是一个非常糟糕的主意。没有办法确定你每次都会得到相同的结果。
最后你的NOT IN子句缺少AND f.dogovor='1'