|
|
Question : SQL Union select TOP N records
|
|
I have sales data in both a current table and an historical table. I need to see the TOP 10 by customer and item. The union needs to combine the open and historical table and show me the TOP 10 combined list. When I run this statement SQL tells me "The multi-part identifier "a.Whatever" could not be bound for every field. This statement worked in SQL Server 2000 but does not work in SQL Server 2005.
select SOPTYPE,SOPNUMBE,ITEMNMBR,ITEMDESC,QUANTITY,UNITPRCE,XTNDPRCE,DOCDATE from ( select TOP 10 a.SOPTYPE,a.SOPNUMBE,a.ITEMNMBR,a.ITEMDESC,a.QUANTITY,a.UNITPRCE,a.XTNDPRCE,b.DOCDATE from sop10200 a,sop10100 b where a.SOPTYPE = b.SOPTYPE and a.SOPNUMBE = b.SOPNUMBE and b.SOPTYPE in (2,4)and a.QUANTITY > 0 order by b.docdate desc ) sub union select a.SOPTYPE,a.SOPNUMBE,a.ITEMNMBR,a.ITEMDESC,a.QUANTITY,a.UNITPRCE,a.XTNDPRCE,b.DOCDATE from ( select TOP 10 a.SOPTYPE,a.SOPNUMBE,a.ITEMNMBR,a.ITEMDESC,a.QUANTITY,a.UNITPRCE,a.XTNDPRCE,b.DOCDATE from sop30300 a,sop30200 b where a.SOPTYPE = b.SOPTYPE and a.SOPNUMBE = b.SOPNUMBE and b.SOPTYPE in (2,4)and a.QUANTITY > 0 order by b.docdate desc ) sub
|
Answer : SQL Union select TOP N records
|
|
try this to sort the results by docdate desc
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
|
SELET * FROM
(
select SOPTYPE,SOPNUMBE,ITEMNMBR,ITEMDESC,QUANTITY,UNITPRCE,XTNDPRCE,DOCDATE
from (
select TOP 10 a.SOPTYPE,a.SOPNUMBE,a.ITEMNMBR,a.ITEMDESC,a.QUANTITY,a.UNITPRCE,a.XTNDPRCE,b.DOCDATE
from sop10200 a,sop10100 b
where a.SOPTYPE = b.SOPTYPE and a.SOPNUMBE = b.SOPNUMBE and b.SOPTYPE in (2,4)and a.QUANTITY > 0
) sub
union
select SOPTYPE,SOPNUMBE,ITEMNMBR,ITEMDESC,QUANTITY,UNITPRCE,XTNDPRCE,DOCDATE
from (
select TOP 10 a.SOPTYPE,a.SOPNUMBE,a.ITEMNMBR,a.ITEMDESC,a.QUANTITY,a.UNITPRCE,a.XTNDPRCE,b.DOCDATE
from sop30300 a,sop30200 b
where a.SOPTYPE = b.SOPTYPE and a.SOPNUMBE = b.SOPNUMBE and b.SOPTYPE in (2,4)and a.QUANTITY > 0
) sub
) T
order by docdate desc
|
Open in New Window
Select All
|
|
|
|
|