Question

these are my table,

http://sqlfiddle.com/#!3/a8087/1

What i'm trying to achieve is insert into another new table by selecting from Tbl2 and CustTable.

E.g:

INSERT INTO tbl3
SELECT TOP(SELECT Counter FROM Tbl2) a.name, a.amount FROM custTable a
INNER JOIN Tbl2 b ON a.custId = b.custid

I want to insert X number of ROW base on CustId's [Counter]. It's not working because Subquery returned more than 1 value.

how can i fix the query in TOP()?

Was it helpful?

Solution

You can use Windowing functions to do rank the rows by customer, and then filter by the counter:

WITH cte as
(
  SELECT a.Name, a.Amount, b.Counter, 
   ROW_NUMBER() OVER (PARTITION BY a.CustID ORDER BY a.Amount DESC) AS RN
  FROM custTable a
  INNER JOIN Tbl2 b ON a.custId = b.custid  
)
SELECT cte.name, cte.amount 
INTO tbl3
FROM cte
WHERE cte.rn <= Counter;

You'll need to choose an ORDER on each customer to determine 'which' of the TOP records get included (I've assumed you want the top amounts here)

I've also used SELECT ... INTO to create table 3 on the fly, but you can INSERT INTO if it is already created.

Updated your SqlFiddle here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top