我在SQL Server 2005中复制结果时遇到了一些麻烦。我之前使用ROW NUMBER
函数来显示我的查询结果,但是我无法在下面看到只显示rownum 1的查询:
SELECT *
FROM (SELECT l.insbilleddate, l.pickupdate, l.patientname, l.inscompanyname AS Payor, l.tripid,
l.sales, l.cost, l.sales-l.cost AS Profit, l.profitpct AS 'Profit Pct', u.pUPFName + ' ' +
u.pUPLName AS Dispatcher, ROW_NUMBER() OVER (PARTITION BY l.tripid ORDER BY d.trDispatchDate
ASC) AS rownum
FROM pUsersPrinters u
INNER JOIN TranslationDispatch d
INNER JOIN v_OLAPdataTR l ON d.trTripid = l.tripid ON u.pUP_id = d.trDispatchedBy
GROUP BY l.insbilleddate, l.pickupdate, l.patientname, l.inscompanyname, l.tripid, l.sales,
l.cost, l.profitpct, u.pUPFName, u.pUPLName, d.trDispatchDate
HAVING l.insbilleddate >= '6/1/2014' And l.insbilleddate < '7/1/2014' AND l.cost > '0' AND
l.profitpct < '30') q1
WHERE rownum = 1
ORDER BY q1.profitpct
每次用户发送旅行时,TranslationDispatch表都会添加一行。如果需要重新分配行程,则数据库不会覆盖原始调度程序,而是添加另一行,其中包含userID,tripID和调度日期。 d.trTripid = l.tripid
比较会导致每个调度程序都显示该行程。
例如,结果显示为:
TripID trDispatchedBy trDispatchDate
1234 Carlos 6/25/2014 10:00
1234 Tim 6/25/2014 10:02
......但我只想在他首先派出旅行时展示卡洛斯。
编辑:我已经在@Vulcronos的帮助下调整了上面的查询以使其工作,方法是添加一个表别名(q1)并将rownum = '1'
转换为rownum = 1
以正确显示我的最终版本结果
答案 0 :(得分:0)
我会尝试:
ROW_NUMBER () OVER ( PARTITION BY l.insbilleddate, l.pickupdate, l.patientname,
l.inscompanyname, l.tripid, l.sales, l.cost, l.profitpct, u.pUPFName, u.pUPLName,
d.trDispatchDate ORDER BY trDispatchDate ASC)
这应该在每个团体最早的发货日期给你一个行号。然后,您可以将整个查询包装在:
select *
from (my_query)
where rownum = 1
答案 1 :(得分:0)
如何添加&#34; TOP 1&#34;到外部查询
SELECT TOP 1 *
FROM(SELECT L.Insbilleddate,
L.Pickupdate,
L.Patientname,
L.Inscompanyname AS Payor,
L.Tripid,
L.Sales,
L.Cost,
L.Sales - L.Cost AS Profit,
L.Profitpct AS 'Profit Pct',
U.Pupfname + ' ' + U.Puplname AS Dispatcher,
ROW_NUMBER()OVER(PARTITION BY L.Tripid ORDER BY D.Trdispatchdate ASC)AS Rownum
FROM Pusersprinters U
INNER JOIN Translationdispatch D
INNER JOIN V_Olapdatatr L ON D.Trtripid = L.Tripid ON U.Pup_Id = D.Trdispatchedby
GROUP BY L.Insbilleddate,
L.Pickupdate,
L.Patientname,
L.Inscompanyname,
L.Tripid,
L.Sales,
L.Cost,
L.Profitpct,
U.Pupfname,
U.Puplname,
D.Trdispatchdate
HAVING L.Insbilleddate >= '6/1/2014'
AND L.Insbilleddate < '7/1/2014'
AND L.Cost > '0'
AND L.Profitpct < '30') A
ORDER BY A.Profitpct;