Click here to Skip to main content
15,923,087 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need query to find the top three magazines having highest subscriptions during last one month from following tables...

Customer table: (cust_id is PK)
cus_id cust_name cust_no
  1      A          123
  2      B          234
  3      C          345

Magazine table: (mag_id is PK)
mag_id  mag_name
  1        Cover drive
  2        top gear
  3        business today
  4        india today
  5        Frontline

Subscription table: (cust_id and mag_id foreign keys)
cust_id  mag_id     start_date  end_date
  1           2      4-7-2013   4-6-2014
  2           2      4-9-2013   4-8-2014
  3           2      4-18-2013  4-17-2014
  2           4      4-18-2013  4-17-2014
  3           4      4-18-2013  4-17-2014
  1           5      4-18-2013  4-17-2014
  2           3      4-18-2013  4-17-2014
  1           1      4-18-2013  4-17-2014

Any help is highly appreciated..!
Posted
Updated 28-Apr-13 3:15am
v2

Try this:
SQL
DECLARE @dFrom DATETIME
DECLARE @dTo DATETIME

SET @dFrom = '01-04-2013'
SET @dTo = '30-04-2013'

SELECT TOP(3) MagazineName, SubscCount
FROM (
    SELECT M.mag_name AS MagazineName, COUNT(S.mad_id) AS SubscCount
    FROM Subscription AS S LEFT JOIN Magazine AS M ON S.mag_id = M.mag_id
    WHERE S.start_date>= @dFrom AND S.end_date<=@dTo
    GROUP BY M.mag_name
) AS T
ORDER BY SubscCount DESC
 
Share this answer
 
v4
hi,

run query

SQL
select top 3 mag_id from Subscription  where start_date > GETDATE()-30 group by mag_id order by mag_id desc


by this you can get top three magaxine ids

thanks.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900