简体   繁体   中英

SQL Server: Comparing dates from multiple records

When a part is created in a table ("ASC_PMA_TBL"), a number is auto-generated. Any "sub-parts" that are subsequently created then have an associated number. So for example, the "master" part might be 18245, and it may have several subparts which would be "18245-50", or "18245-40", etc. Subparts are always identified by having the master part number, followed by a '-' then a two-digit number. Each sub part has a date associated with it ("EO_DATE"). All I want to do is display records where the "master" dates don't match each of the sub-parts dates. All data is in the one table "ASC_PMA_TBL".

Normally this would be easily achieved using a join. However in the database, the subparts are not related to their master through the use of foreign keys, so I'm having to find a different way of doing things.

Furthermore, the date field is a date/ time field, so to compare them I first have to convert the field into a date only field. I can do this, but then am unable to use the alias in my query!

Any help is much appreciated:)

I have tried creating temporary tables and using subqueries, but cannot solve this problem:(

UPDATE: Managed to solve the problem using temporary tables, truncating the part number of the sub-parts to match the master parts, and then joining the two to compare the dates. Might be messy, but it works!

SELECT
    PMA_PART_ONLY,
    CONVERT(DATE,PMA_EFFECT_DATE_OFF) As 'EO_DATE'
INTO
    ##MParts
FROM
    ASC_PMA_TBL
WHERE
    (PMA_PROC_CODE = 'M') AND
    (PMA_EFFECT_DATE_OFF IS NOT NULL)
SELECT
    PMA_PART_ONLY,
    CONVERT(DATE,PMA_EFFECT_DATE_OFF) As 'EO_DATE',
    SUBSTRING(PMA_PART_ONLY,0,CHARINDEX('-',PMA_PART_ONLY,0)) As 'MP_NO'
INTO
    ##SParts
FROM
    ASC_PMA_TBL
WHERE
    (PMA_PROC_CODE = 'S') AND
    (PMA_EFFECT_DATE_OFF IS NOT NULL)
SELECT
    ##SParts.PMA_PART_ONLY As 'SUB_PART_NO',
    ##MParts.EO_DATE As 'M_PART_DATE',
    ##SParts.EO_DATE As 'S_PART_DATE'
FROM
    ##MParts INNER JOIN ##SParts ON ##SParts.MP_NO = ##MParts.PMA_PART_ONLY
WHERE
    (##MParts.EO_DATE <> ##SParts.EO_DATE)
ORDER BY
    SUB_PART_NO DESC
    
DROP TABLE ##MParts
DROP TABLE ##SParts

If you want to compare just dates and not times you gotta convert the dates:

select *
from ASC_PMA_TBL master
inner join ASC_PMA_TBL parts
 ON parts.number like CAST(master.number AS VARCHAR(30)) + '[_]%'
where CAST(master.EO_DATE AS DATE) <> CAST(parts.EO_DATE AS DATE)

That's the main idea, get all master and parts where part number is like master number + underscope.

Note that you have to escape "_" in []-quotes when performing LIKE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM