Question

Im trying to create a nested SQL statement with multiple Nested Select Statements, to be used on a record set import in excel vba.

What i want to do is create something like:

SELECT
    N.LimitN,
    Sum(N.amountN),
    Sum(N1.amountN1)
FROM (
    SELECT year as yearN, Sum(amount) as amountN, limit as limitN
    FROM table1
    WHERE year = 2013
    GROUP BY year, limit) as N
JOIN (
    SELECT year as yearN1, Sum(amount) as amountN1, limit as limitN1
    FROM table1
    WHERE year = 2014
    GROUP BY year, limit) as N1
ON N.LimitN = N1.LimitN1
GROUP BY N.LimitN
ORDER BY N.LimitN;

So that if my Raw data is like this:

Year       Amount        Limit
2013        100           20
2013         90           30
2013        120           40
2013          5           20
2013        100           30
2013        105           40
2013        150           50
2014        115           20
2014         50           30
2014         95           40
2014        110           50
2014         30           20

My Resulting Table/record set will be like this:

Limit     AmountN (i.e. 2013)   Amount N1 (i.e. 2014)
 20               105                    145
 30               190                     50
 40               225                     95
 50               150                    110

Thanks in Advance

Peter

Était-ce utile?

La solution

It feels like you're overcomplicating the query a little, what you want is just a year wise sum of amount, grouped by limit. This can be done using a CASE;

SELECT 
  limit, 
  SUM(CASE WHEN year=2013 THEN amount ELSE 0 END) amountN,
  SUM(CASE WHEN year=2014 THEN amount ELSE 0 END) amountN1
FROM myTable
GROUP BY limit
ORDER BY limit;

An SQLfiddle to test with.

(if we're talking Access here, you will need to use IIF instead of CASE)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top