Incorrect sort order on using Top 1 with Unique Identfier Column views incorrect results in query

  • Hi

    Im using a view [dbo].[CustomerBrokerView_PMR2] , in orderto do a join and select the top 1 Primary Key
    value our of this view

    My code is as follows:

    FROM [dbo].[SalesReportView] srv

    INNER JOIN dbo.CustomerView cv ON srv.CustomerId = cv.customerid

    innerJOIN [dbo].[CustomerBrokerView_PMR2] cb ON cb.customerid = cv.CustomerID AND cb.[AccountOffice] = cv.[OfficeLocation]

    AND

    cb.[customerBrokerid] =

    (

                                                                                             SELECT TOP 1[customerBrokerid]

                                                                                             FROM

                                                                                                     [dbo].[CustomerBrokerView_PMR2]CBV

                                                                                              WHERE

                                                                                                    CBV.[customerid]= cv.CustomerID 

                                                                                             AND

                                                                                                    cbv.[AccountOffice]  =cv.[OfficeLocation]

                                                                                             AND

                                                                                                     cbv.[CreatedAt]  <=  srv.CreatedAt

                                                                                             ORDER BYcbv.createdat desc


    My data in [dbo]
    .[CustomerBrokerView_PMR2] is as follows:

    customerBrokerid

    customerid

    CustomerName

    CreatedAt

    AccountOffice

    C9565947-AA73-49B3-9CF7-C2218E93B2E3

    8E0CB473-F889-42EC-9646-99E4A6FB0EF3

    SWFC ( Sheffield Wednesday FC )

    26/08/2015 17:36

    London

    1A03E7EB-0DEF-4CE4-B5A9-0187F86E6E58

    8E0CB473-F889-42EC-9646-99E4A6FB0EF3

    SWFC ( Sheffield Wednesday FC )

    22/02/2017 14:01

    London

    A sorting [dbo].[CustomerBrokerView_PMR2]  in date descending order , will yield
    the value 22/07/2017  14:01
    I know that the value for srv.CreatedAt will return '016-01-21 00:00:00.000'and therefore
    I expect no value to be returned

    however a value is being returned because the inner Top 1 query  forSelect Top 1
    should give me the value for the 2nd row shown above in Red and white

    what is going on here and why does sorting a view with a unique identifier giveme the wrong result?

    is there something I need to do in the casting in my datatypes in the joins orfields in my view??

  • With only a portion of the code being run, no DDL for the tables/views involved and no sample data that is representative of the problem domain and the problem (sense we also don't have access to your servers and databases to see for ourselves) we can't really give you a clear answer.

    As this appears to be a correlated sub-query, you may also want to look at the data in the table outside the query providing date information.

  • The screenshot doesn't show where the data is coming from, so all we can do is guess.

    If you supply DDL and consumable sample data that shows the problem, it would be much easier.

    Thom~

    Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
    Larnu.uk

  • Hi there

    OK here goes

    This is my complete query

    SELECT

    srv.salesreportid,

    cv.CustomerName,

    cv.officelocation,

    cb.[AccountOffice],

    cv.CustomerId,

    cv.Division AS DepartmentType,

    srv.SalesReportDate,

    SRV.CreatedAt,

    cb.BrokerCode,

    cb.[CreatedAt] AS Cbv_effectiveDate,

    cb.customerBrokerid,

    srv.[CreatedAt] AS Updatedat,

    CASE

    WHEN srv.ContactType IN ('TELEPHONE')

    THEN 1

    ELSE 0

    END AS Calls

    FROM [dbo].[SalesReportView] srv

    INNER JOIN dbo.CustomerView cv ON srv.CustomerId = cv.customerid

    inner JOIN [dbo].[CustomerBrokerView_PMR2] cb ON cb.customerid = cv.CustomerIDAND cb.[AccountOffice] = cv.[OfficeLocation]

    AND

    cb.[customerBrokerid] =

    (

    SELECT TOP 1 [customerBrokerid]

    FROM

    [dbo].[CustomerBrokerView_PMR2] CBV

    WHERE

    CBV.[customerid] = cv.CustomerID

    AND

    cbv.[AccountOffice]= cv.[OfficeLocation]

    AND

    cbv.[CreatedAt] <= srv.CreatedAt

    ORDER BY cbv.createdat desc

    )

    WHERE

    YEAR(srv.CreatedAt) = 2016

    AND

    MONTH(srv.CreatedAt) = 1

    AND

    srv.ContactType = 'TELEPHONE'

    AND

    srv.BrokerCode = 'LONCOMPP'

    ORDER BY cb.CustomerName

    -----------------------
    DDL for views
    1) dbo.SalesReportView

    Column_nameTypeComputedLengthPrecScaleNullableCollation
    IDuniqueidentifierno16          noNULL
    CustomerIduniqueidentifierno16          noNULL
    salesReportIDintno4100yesNULL
    SalesReportDatedatetimeno8          noNULL
    BrokerCodenvarcharno400          yesLatin1_General_CI_AS
    CustomerNamenvarcharno510          noLatin1_General_CI_AS
    ContactForenamenvarcharno510          yesLatin1_General_CI_AS
    ContactSurnamenvarcharno510          yesLatin1_General_CI_AS
    ContactTypenvarcharno400          yesLatin1_General_CI_AS
    ReportTypenvarcharno-1          noLatin1_General_CI_AS
    CreatedAtdatetimeno8          noNULL
    CreatedBynvarcharno400          yesLatin1_General_CI_AS
    EstimatedChartersPerAnnumnumericno13272yesNULL
    ContactMoodnvarcharno400          yesLatin1_General_CI_AS
    CityVisitednvarcharno510          yesLatin1_General_CI_AS
    CountryVisitednvarcharno400          yesLatin1_General_CI_AS

    2)   dbo.CustomerView

    Column_nameTypeLengthNullableCollation
    CustomerIDnvarchar200yesLatin1_General_CI_AS
    CustomerGUIDuniqueidentifier16noNULL
    CustomerNamenvarchar510noLatin1_General_CI_AS
    IsSameAsACSNamebit1noNULL
    PostalNamenvarchar510yesLatin1_General_CI_AS
    CustomerSourcenvarchar400yesLatin1_General_CI_AS
    Divisionnvarchar400noLatin1_General_CI_AS
    Brokeruniqueidentifier16yesNULL
    PrimaryBrokerContactuniqueidentifier16yesNULL
    BrokerCodenvarchar400yesLatin1_General_CI_AS
    AddressLinesnvarchar-1yesLatin1_General_CI_AS
    Addressuniqueidentifier16yesNULL
    Townnvarchar510yesLatin1_General_CI_AS
    Countynvarchar510yesLatin1_General_CI_AS
    Statenvarchar400yesLatin1_General_CI_AS
    Postcodenvarchar400yesLatin1_General_CI_AS
    Countrynvarchar400yesLatin1_General_CI_AS
    Websitenvarchar510yesLatin1_General_CI_AS
    DefaultInvoicingContactbit1noNULL
    BusinessTypenvarchar400yesLatin1_General_CI_AS
    EstimatedChartersPerYearnumeric13yesNULL
    IsVATRegisteredbit1noNULL
    VATNumbernvarchar510yesLatin1_General_CI_AS
    IBOS_NT_UserNamenvarchar400yesLatin1_General_CI_AS
    OfficeLocationnvarchar400noLatin1_General_CI_AS
    CreatedAtdatetime8yesNULL

    3) dbo.CustomerBrokerView_PMR2

    Column_nameTypeComputedLengthCollation
    customerBrokeriduniqueidentifierno16NULL
    customeriduniqueidentifierno16NULL
    CustomerNamenvarcharno510Latin1_General_CI_AS
    CreatedAtdatetimeno8NULL
    BrokerCodenvarcharno400Latin1_General_CI_AS
    AccountOfficenvarcharno400Latin1_General_CI_AS

    SAMPLE DATA FROM VIEWS

    [dbo].[SalesReportView] 
    IDCustomerIdsalesReportIDSalesReportDateBrokerCodeCustomerNameContactForenameContactSurnameContactTypeReportTypeCreatedAtCreatedByEstimatedChartersPerAnnumContactMoodCityVisitedCountryVisited
    33E32998-8102-4AA2-8A35-5AEB74DDB1A98E0CB473-F889-42EC-9646-99E4A6FB0EF351287922/02/2017 00:00LONCOMPPSWFC ( Sheffield Wednesday FC )NULLNULLTelephoneCouldn't get through receoption. Tried twice now. Always in meetings. Tried bullshitting when asked the reason for the calls. Just said we'd been working on some things with her. PP22/02/2017 14:17pphilpott3FriendlyNULLNULL
    A4AD5922-9EE4-4205-A5C0-4B3A6BCF12AA8E0CB473-F889-42EC-9646-99E4A6FB0EF351288922/02/2017 00:00LONCOMPPSWFC ( Sheffield Wednesday FC )LindseyTaylorTelephoneFollowed up with brochures in the post and email. PP 22/02/2017 14:50pphilpott3FriendlyNULLNULL
    7754C0B8-5B3D-4C0A-80C9-3AFAF2853C588E0CB473-F889-42EC-9646-99E4A6FB0EF336245921/01/2016 00:00LONCOMPPSWFC ( Sheffield Wednesday FC )LindseyTaylorTelephoneLindsey is the contact. Wasn't able to get through but was told to send her an email (don't think they like to put people directly through to their staff if they aren't returning a call. PP21/01/2016 15:16pphilpottNULLFriendlyNULLNULL
    1E0A7FD7-CB21-4DEC-A682-D4F73E5AC9338E0CB473-F889-42EC-9646-99E4A6FB0EF331259026/08/2015 00:00LONCOMPPSWFC ( Sheffield Wednesday FC )AndyDaykinTelephoneSent Andy a brief note on the Soccerex networking tool to let him know we'll be there. Will also drop him a call and email early next week if I don't get a response. PP26/08/2015 17:39pphilpottNULLFriendlyNULLNULL

    [dbo].[CustomerView] 
    CustomerIDCustomerGUIDCustomerNameIsSameAsACSNamePostalNameCustomerSourceDivisionBrokerPrimaryBrokerContactBrokerCodeAddressLinesAddressTownCountyStatePostcodeCountryWebsiteDefaultInvoicingContactBusinessTypeEstimatedChartersPerYearIsVATRegisteredVATNumberIBOS_NT_UserNameOfficeLocationCreatedAt
    8E0CB473-F889-42EC-9646-99E4A6FB0EF38E0CB473-F889-42EC-9646-99E4A6FB0EF3SWFC ( Sheffield Wednesday FC )0NULLOtherCOMMJ4672B0B3-C4B4-4B05-9298-8CB4B6D586B85D66B0E7-8F36-429E-92A8-70E5E4F47FE1LONCOMPPHillsborough Stadium  Leppings Lane  AF516A57-465E-4021-B59A-DC292CB1526FSheffieldNULLNULLS6 1SWUnited Kingdomhttp://www.swfc.co.uk0Sport30NULLNULLLondon47:43.0

    [dbo].[CustomerBrokerView_PMR2] 
    customerBrokeridcustomeridCustomerNameCreatedAtBrokerCodeAccountOffice
    47002475-B3DE-4715-B152-13D89CE1B9348E0CB473-F889-42EC-9646-99E4A6FB0EF3SWFC ( Sheffield Wednesday FC )16/05/2016 12:27LONCOMWSLondon
    9BAD3DE0-5124-4852-BD19-993322F663F28E0CB473-F889-42EC-9646-99E4A6FB0EF3SWFC ( Sheffield Wednesday FC )17/04/2012 18:47LONCOMSHLondon
    C9565947-AA73-49B3-9CF7-C2218E93B2E38E0CB473-F889-42EC-9646-99E4A6FB0EF3SWFC ( Sheffield Wednesday FC )26/08/2015 17:36LONCOMPPLondon
    1A03E7EB-0DEF-4CE4-B5A9-0187F86E6E588E0CB473-F889-42EC-9646-99E4A6FB0EF3SWFC ( Sheffield Wednesday FC )22/02/2017 14:01LONCOMPPLondon
    977EF938-1014-4ABD-8FB8-D9C145AC0A318E0CB473-F889-42EC-9646-99E4A6FB0EF3SWFC ( Sheffield Wednesday FC )03/10/2012 16:59CZLondon
  • We need it in a consumable format, please. Have a look at the link in my signature on how to achieve this.

    Thom~

    Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
    Larnu.uk

  • Also, does the sample data demonstrate the problem you are experiencing?

    If so, what should it return if working correctly?

  • chris.asaipillai-624309 - Thursday, March 16, 2017 9:23 AM

    Hi

    Im using a view [dbo].[CustomerBrokerView_PMR2] , in orderto do a join and select the top 1 Primary Key
    value our of this view

    My code is as follows:

    FROM [dbo].[SalesReportView] srv

    INNER JOIN dbo.CustomerView cv ON srv.CustomerId = cv.customerid

    innerJOIN [dbo].[CustomerBrokerView_PMR2] cb ON cb.customerid = cv.CustomerID AND cb.[AccountOffice] = cv.[OfficeLocation]

    AND

    cb.[customerBrokerid] =

    (

                                                                                             SELECT TOP 1[customerBrokerid]

                                                                                             FROM

                                                                                                     [dbo].[CustomerBrokerView_PMR2]CBV

                                                                                              WHERE

                                                                                                    CBV.[customerid]= cv.CustomerID 

                                                                                             AND

                                                                                                    cbv.[AccountOffice]  =cv.[OfficeLocation]

                                                                                             AND

                                                                                                     cbv.[CreatedAt]  <=  srv.CreatedAt

                                                                                             ORDER BYcbv.createdat desc


    My data in [dbo]
    .[CustomerBrokerView_PMR2] is as follows:

    customerBrokerid

    customerid

    CustomerName

    CreatedAt

    AccountOffice

    C9565947-AA73-49B3-9CF7-C2218E93B2E3

    8E0CB473-F889-42EC-9646-99E4A6FB0EF3

    SWFC ( Sheffield Wednesday FC )

    26/08/2015 17:36

    London

    1A03E7EB-0DEF-4CE4-B5A9-0187F86E6E58

    8E0CB473-F889-42EC-9646-99E4A6FB0EF3

    SWFC ( Sheffield Wednesday FC )

    22/02/2017 14:01

    London

    A sorting [dbo].[CustomerBrokerView_PMR2]  in date descending order , will yield
    the value 22/07/2017  14:01
    I know that the value for srv.CreatedAt will return '016-01-21 00:00:00.000'and therefore
    I expect no value to be returned

    however a value is being returned because the inner Top 1 query  forSelect Top 1
    should give me the value for the 2nd row shown above in Red and white

    what is going on here and why does sorting a view with a unique identifier giveme the wrong result?

    is there something I need to do in the casting in my datatypes in the joins orfields in my view??

    No, it won't.  The srv.CreatedAt date of 21/01/2016 15:16 will not include the date 22/02/2107 14:01 as it is not less than or equal to 21/01/2016 15:16.

  • Lynn Pettis - Thursday, March 16, 2017 10:05 AM

    Also, does the sample data demonstrate the problem you are experiencing?

    If so, what should it return if working correctly?

    Hi Lynn

    The inner query should return a value for [CreatedAt] from [dbo.CustomerBrokerView_PMR2] of  '2017-02-22 14:01:16.783'   with ORDER BY cbv.createdAt  desc

    Now the part of the query
    where   cbv.CreatedAt  =  '2017-02-22 14:01:16.783'     and srv.CreatedAt  = 2016-01-21 00:00:00.000
    Means that  

    cbv.[CreatedAt] <= srv.Created At  Returns no records   (The Result I want)

    However,

    ORDER

    BY cbv.createdat desc  returns a value  of '2015-08-26 17:36:55.243'  for cbv.CreatedAt

    Therefore when cbv.[CreatedAt] <= srv.Created  is  run
    '2015-08-26 17:36:55.243'  <= 2016-01-21 00:00:00.000   (Result I don't want)

    why does sorting dbo.CustomerBrokerView_PMR2 in my inner query not give me the value for 2017-02-22 14:01:16.783
    for the CreatedAt column?

  • I think what you're after here is a CROSS APPLY, so you can limit your result that way.

    This is untested, however, instead of your INNER JOIN to [CustomerBrokerView] does this work?
    CROSS APPLY (SELECT TOP 1 *
                 FROM [dbo].[CustomerBrokerView_PMR2] ca
                 WHERE ca.customerid = cv.CustomerID
                   AND ca.[AccountOffice] = cv.[OfficeLocation]
                   AND ca.[CreatedAt] <= srv.CreatedAt
                 ORDER BY ca.Createdat DESC) cb

    If not, does it get you close, and are you able to amend this to get what you need?

    Thom~

    Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
    Larnu.uk

  • chris.asaipillai-624309 - Thursday, March 16, 2017 10:29 AM

    Lynn Pettis - Thursday, March 16, 2017 10:05 AM

    Also, does the sample data demonstrate the problem you are experiencing?

    If so, what should it return if working correctly?

    Hi Lynn

    The inner query should return a value for [CreatedAt] from [dbo.CustomerBrokerView_PMR2] of  '2017-02-22 14:01:16.783'   with ORDER BY cbv.createdAt  desc

    Now the part of the query
    where   cbv.CreatedAt  =  '2017-02-22 14:01:16.783'     and srv.CreatedAt  = 2016-01-21 00:00:00.000
    Means that  

    cbv.[CreatedAt] <= srv.Created At  Returns no records   (The Result I want)

    However,

    ORDER

    BY cbv.createdat desc  returns a value  of '2015-08-26 17:36:55.243'  for cbv.CreatedAt

    Therefore when cbv.[CreatedAt] <= srv.Created  is  run
    '2015-08-26 17:36:55.243'  <= 2016-01-21 00:00:00.000   (Result I don't want)

    why does sorting dbo.CustomerBrokerView_PMR2 in my inner query not give me the value for 2017-02-22 14:01:16.783
    for the CreatedAt column?

    This sub-query:

                                        SELECT TOP 1 [customerBrokerid]
                                        FROM
                                          [dbo].[CustomerBrokerView_PMR2] CBV
                                        WHERE
                                          CBV.[customerid] = cv.CustomerID
                                          AND
                                          cbv.[AccountOffice] = cv.[OfficeLocation]
                                          AND
                                          cbv.[CreatedAt] <= srv.CreatedAt
                                        ORDER BY
                                          cbv.createdat desc

    Filters the data down to all the data that has a CreatedAt date that is less than or equal to 21/01/2016 15:16 which is the CreatedAt date from the outer query.  Sorting this data by CreatedAt in descending order
    puts the row of data with the date 26/08/2015 17:36 at the top which is what is returned by the TOP 1.

  • Lynn Pettis - Thursday, March 16, 2017 10:50 AM

    chris.asaipillai-624309 - Thursday, March 16, 2017 10:29 AM

    Lynn Pettis - Thursday, March 16, 2017 10:05 AM

    Also, does the sample data demonstrate the problem you are experiencing?

    If so, what should it return if working correctly?

    Hi Lynn

    The inner query should return a value for [CreatedAt] from [dbo.CustomerBrokerView_PMR2] of  '2017-02-22 14:01:16.783'   with ORDER BY cbv.createdAt  desc

    Now the part of the query
    where   cbv.CreatedAt  =  '2017-02-22 14:01:16.783'     and srv.CreatedAt  = 2016-01-21 00:00:00.000
    Means that  

    cbv.[CreatedAt] <= srv.Created At  Returns no records   (The Result I want)

    However,

    ORDER

    BY cbv.createdat desc  returns a value  of '2015-08-26 17:36:55.243'  for cbv.CreatedAt

    Therefore when cbv.[CreatedAt] <= srv.Created  is  run
    '2015-08-26 17:36:55.243'  <= 2016-01-21 00:00:00.000   (Result I don't want)

    why does sorting dbo.CustomerBrokerView_PMR2 in my inner query not give me the value for 2017-02-22 14:01:16.783
    for the CreatedAt column?

    This sub-query:

                                        SELECT TOP 1 [customerBrokerid]
                                        FROM
                                          [dbo].[CustomerBrokerView_PMR2] CBV
                                        WHERE
                                          CBV.[customerid] = cv.CustomerID
                                          AND
                                          cbv.[AccountOffice] = cv.[OfficeLocation]
                                          AND
                                          cbv.[CreatedAt] <= srv.CreatedAt
                                        ORDER BY
                                          cbv.createdat desc

    Filters the data down to all the data that has a CreatedAt date that is less than or equal to 21/01/2016 15:16 which is the CreatedAt date from the outer query.  Sorting this data by CreatedAt in descending order
    puts the row of data with the date 26/08/2015 17:36 at the top which is what is returned by the TOP 1.

    Hi Lynn

    Ok is there a way that I can force the value of 22/02/2017 14:01 to the top?

  • Thom A - Thursday, March 16, 2017 10:37 AM

    I think what you're after here is a CROSS APPLY, so you can limit your result that way.

    This is untested, however, instead of your INNER JOIN to [CustomerBrokerView] does this work?
    CROSS APPLY (SELECT TOP 1 *
                 FROM [dbo].[CustomerBrokerView_PMR2] ca
                 WHERE ca.customerid = cv.CustomerID
                   AND ca.[AccountOffice] = cv.[OfficeLocation]
                   AND ca.[CreatedAt] <= srv.CreatedAt
                 ORDER BY ca.Createdat DESC) cb

    If not, does it get you close, and are you able to amend this to get what you need?

    Hi
    That didn't work for me im afraid. I got multiple records back

  • chris.asaipillai-624309 - Thursday, March 16, 2017 10:55 AM

    Lynn Pettis - Thursday, March 16, 2017 10:50 AM

    chris.asaipillai-624309 - Thursday, March 16, 2017 10:29 AM

    Lynn Pettis - Thursday, March 16, 2017 10:05 AM

    Also, does the sample data demonstrate the problem you are experiencing?

    If so, what should it return if working correctly?

    Hi Lynn

    The inner query should return a value for [CreatedAt] from [dbo.CustomerBrokerView_PMR2] of  '2017-02-22 14:01:16.783'   with ORDER BY cbv.createdAt  desc

    Now the part of the query
    where   cbv.CreatedAt  =  '2017-02-22 14:01:16.783'     and srv.CreatedAt  = 2016-01-21 00:00:00.000
    Means that  

    cbv.[CreatedAt] <= srv.Created At  Returns no records   (The Result I want)

    However,

    ORDER

    BY cbv.createdat desc  returns a value  of '2015-08-26 17:36:55.243'  for cbv.CreatedAt

    Therefore when cbv.[CreatedAt] <= srv.Created  is  run
    '2015-08-26 17:36:55.243'  <= 2016-01-21 00:00:00.000   (Result I don't want)

    why does sorting dbo.CustomerBrokerView_PMR2 in my inner query not give me the value for 2017-02-22 14:01:16.783
    for the CreatedAt column?

    This sub-query:

                                        SELECT TOP 1 [customerBrokerid]
                                        FROM
                                          [dbo].[CustomerBrokerView_PMR2] CBV
                                        WHERE
                                          CBV.[customerid] = cv.CustomerID
                                          AND
                                          cbv.[AccountOffice] = cv.[OfficeLocation]
                                          AND
                                          cbv.[CreatedAt] <= srv.CreatedAt
                                        ORDER BY
                                          cbv.createdat desc

    Filters the data down to all the data that has a CreatedAt date that is less than or equal to 21/01/2016 15:16 which is the CreatedAt date from the outer query.  Sorting this data by CreatedAt in descending order
    puts the row of data with the date 26/08/2015 17:36 at the top which is what is returned by the TOP 1.

    Hi Lynn

    Ok is there a way that I can force the value of 22/02/2017 14:01 to the top?

    Change or remove this part of the sub-query, AND cbv.[CreatedAt] <= srv.CreatedAt, but it is obviously there for a reason.
    Or, change the criteria for the main query to change the date range being queried which based on your post is srv.CreatedAt >= '2016-01-01' and srv.CreatedAt < '2016-02-01'.
    Your query actually uses YEAR(srv.CreatedAt) = 2016 and MONTH(srv.CreatedAt) = 1, all of which is non-sargable and won't use an index if available.

  • Lynn Pettis - Thursday, March 16, 2017 11:12 AM

    chris.asaipillai-624309 - Thursday, March 16, 2017 10:55 AM

    Lynn Pettis - Thursday, March 16, 2017 10:50 AM

    chris.asaipillai-624309 - Thursday, March 16, 2017 10:29 AM

    Lynn Pettis - Thursday, March 16, 2017 10:05 AM

    Also, does the sample data demonstrate the problem you are experiencing?

    If so, what should it return if working correctly?

    Hi Lynn

    The inner query should return a value for [CreatedAt] from [dbo.CustomerBrokerView_PMR2] of  '2017-02-22 14:01:16.783'   with ORDER BY cbv.createdAt  desc

    Now the part of the query
    where   cbv.CreatedAt  =  '2017-02-22 14:01:16.783'     and srv.CreatedAt  = 2016-01-21 00:00:00.000
    Means that  

    cbv.[CreatedAt] <= srv.Created At  Returns no records   (The Result I want)

    However,

    ORDER

    BY cbv.createdat desc  returns a value  of '2015-08-26 17:36:55.243'  for cbv.CreatedAt

    Therefore when cbv.[CreatedAt] <= srv.Created  is  run
    '2015-08-26 17:36:55.243'  <= 2016-01-21 00:00:00.000   (Result I don't want)

    why does sorting dbo.CustomerBrokerView_PMR2 in my inner query not give me the value for 2017-02-22 14:01:16.783
    for the CreatedAt column?

    This sub-query:

                                        SELECT TOP 1 [customerBrokerid]
                                        FROM
                                          [dbo].[CustomerBrokerView_PMR2] CBV
                                        WHERE
                                          CBV.[customerid] = cv.CustomerID
                                          AND
                                          cbv.[AccountOffice] = cv.[OfficeLocation]
                                          AND
                                          cbv.[CreatedAt] <= srv.CreatedAt
                                        ORDER BY
                                          cbv.createdat desc

    Filters the data down to all the data that has a CreatedAt date that is less than or equal to 21/01/2016 15:16 which is the CreatedAt date from the outer query.  Sorting this data by CreatedAt in descending order
    puts the row of data with the date 26/08/2015 17:36 at the top which is what is returned by the TOP 1.

    Hi Lynn

    Ok is there a way that I can force the value of 22/02/2017 14:01 to the top?

    Change or remove this part of the sub-query, AND cbv.[CreatedAt] <= srv.CreatedAt, but it is obviously there for a reason.
    Or, change the criteria for the main query to change the date range being queried which based on your post is srv.CreatedAt >= '2016-01-01' and srv.CreatedAt < '2016-02-01'.
    Your query actually uses YEAR(srv.CreatedAt) = 2016 and MONTH(srv.CreatedAt) = 1, all of which is non-sargable ant won't use an index if available.

    Hi Lynn

    cbv.CreatedAt <= srv.CreatedAt  in the query .
    I also changed the criteria for the query   for

    srv.CreatedAt >= '2016-01-01' and srv.CreatedAt < '2016-02-01'

    But still get cbv_effectiveDate  = 2015-08-26 17:36:55.243  and salesReportDate = 2016-01-21 00:00:00.000

  • chris.asaipillai-624309 - Thursday, March 16, 2017 11:27 AM

    Lynn Pettis - Thursday, March 16, 2017 11:12 AM

    chris.asaipillai-624309 - Thursday, March 16, 2017 10:55 AM

    Lynn Pettis - Thursday, March 16, 2017 10:50 AM

    chris.asaipillai-624309 - Thursday, March 16, 2017 10:29 AM

    Lynn Pettis - Thursday, March 16, 2017 10:05 AM

    Also, does the sample data demonstrate the problem you are experiencing?

    If so, what should it return if working correctly?

    Hi Lynn

    The inner query should return a value for [CreatedAt] from [dbo.CustomerBrokerView_PMR2] of  '2017-02-22 14:01:16.783'   with ORDER BY cbv.createdAt  desc

    Now the part of the query
    where   cbv.CreatedAt  =  '2017-02-22 14:01:16.783'     and srv.CreatedAt  = 2016-01-21 00:00:00.000
    Means that  

    cbv.[CreatedAt] <= srv.Created At  Returns no records   (The Result I want)

    However,

    ORDER

    BY cbv.createdat desc  returns a value  of '2015-08-26 17:36:55.243'  for cbv.CreatedAt

    Therefore when cbv.[CreatedAt] <= srv.Created  is  run
    '2015-08-26 17:36:55.243'  <= 2016-01-21 00:00:00.000   (Result I don't want)

    why does sorting dbo.CustomerBrokerView_PMR2 in my inner query not give me the value for 2017-02-22 14:01:16.783
    for the CreatedAt column?

    This sub-query:

                                        SELECT TOP 1 [customerBrokerid]
                                        FROM
                                          [dbo].[CustomerBrokerView_PMR2] CBV
                                        WHERE
                                          CBV.[customerid] = cv.CustomerID
                                          AND
                                          cbv.[AccountOffice] = cv.[OfficeLocation]
                                          AND
                                          cbv.[CreatedAt] <= srv.CreatedAt
                                        ORDER BY
                                          cbv.createdat desc

    Filters the data down to all the data that has a CreatedAt date that is less than or equal to 21/01/2016 15:16 which is the CreatedAt date from the outer query.  Sorting this data by CreatedAt in descending order
    puts the row of data with the date 26/08/2015 17:36 at the top which is what is returned by the TOP 1.

    Hi Lynn

    Ok is there a way that I can force the value of 22/02/2017 14:01 to the top?

    Change or remove this part of the sub-query, AND cbv.[CreatedAt] <= srv.CreatedAt, but it is obviously there for a reason.
    Or, change the criteria for the main query to change the date range being queried which based on your post is srv.CreatedAt >= '2016-01-01' and srv.CreatedAt < '2016-02-01'.
    Your query actually uses YEAR(srv.CreatedAt) = 2016 and MONTH(srv.CreatedAt) = 1, all of which is non-sargable ant won't use an index if available.

    Hi Lynn

    cbv.CreatedAt <= srv.CreatedAt  in the query .
    I also changed the criteria for the query   for

    srv.CreatedAt >= '2016-01-01' and srv.CreatedAt < '2016-02-01'

    But still get cbv_effectiveDate  = 2015-08-26 17:36:55.243  and salesReportDate = 2016-01-21 00:00:00.000

    So your query is still going to return the data for the row with this ID: 7754C0B8-5B3D-4C0A-80C9-3AFAF2853C58, which will still return this date/time: 21/01/2016 15:16, which will still limit the data returned by the
    sub-query to all dates less than or equal to that date which will exclude the date you want: 22/02/2017 14:50.

    I don't know what to tell you to get what you want.

Viewing 15 posts - 1 through 15 (of 15 total)

You must be logged in to reply to this topic. Login to reply