1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Filtering data on the dataset using the same dataset for subquery filtering

Discussion in 'MySQL' started by mbaric, Oct 15, 2013.

  1. #1
    I am having trouble writing exactly 4 queries in mysql.

    Here is the view I am using for queries: http://pastie.org/8403299

    Here is the Raw Data you can check
    goo.gl/z7Vv9X

    which you can check.

    What is needed:

    1) Gained students are those who exist in the selected / filtered month and don't exist in the previous month.

    2) Lost students are those who exist in the previous month of the selected / filtered month and don't exist in the selected / filtered month.

    3) Get a list of all lost students since the start of the center till now().

    4) Get a list of all gained students since the start of center till now.

    I am currently stuck with query 1) (Gained students are those who exist in the selected / filtered month and don't exist in the previous month.)

    I have written it like that (see just below), but I get the same number of rows back if I haven't filtered anything... uff.

    SELECT *
    FROM lessons_master_001 my1
    WHERE NOT EXISTS
    (
    SELECT 0
    FROM lessons_master_001 my2
    WHERE
    my1.student_id = my2.`student_id`
    AND
    my1.teacher_id = my2.teacher_id
    AND
    my1.`student_payment_id`= my2.`student_payment_id`AND
    CONCAT(CAST(MONTH(DATE_ADD(my1.Lesson_Booking_Date, INTERVAL -1 MONTH))AS CHAR(20)),CAST(YEAR(DATE_ADD(my1.Lesson_Booking_Date, INTERVAL -1 MONTH))AS CHAR(20)))
    =
    CONCAT(CAST(MONTH(my2.`Lesson_Booking_Date`)AS CHAR(20)),CAST(YEAR(my2.`Lesson_Booking_Date`)AS CHAR(20)))
    )
    PHP:
    My logic is like this so I take everything from the view lessons_master_001 and give alias my1 and in the NOT EXISTS clause I am giving to the same dataset alias my2, then join those ID's that are also used in view lessons_master_001 and then try to connect previous month from data set my1 with current month from data set my2.

    I am using DATE_ADD function to subtract month from current date and practically get date - 1 month.

    I would really appreciate any help you will provide, cause I lost 2 days already on it with no progress in front.

    Thank you in advance.
     
    Last edited: Oct 15, 2013
    mbaric, Oct 15, 2013 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,500
    Likes Received:
    4,460
    Best Answers:
    123
    Trophy Points:
    665
    #2
    sarahk, Oct 21, 2013 IP