Вопрос

I am trying to set the following query so that it only selects any data from the DaysMov table (A) if the nested Select finds a matching date in the Calendar table (B). Currently in such a case it just returns nothing for "dayMov" but still selects the other data from table A.

Can someone tell me how I can achieve this, e.g. by using Where or Case ?

SELECT      
            (
                SELECT      B.calendar_DT
                FROM        Calendar B
                WHERE       B.year_id = @selYear AND B.month_of_year = A.calMonth AND B.day_of_week = A.calDay AND (B.day_of_month BETWEEN A.calFrom AND A.calTill)
            ) AS dayMov,
            A.countries,
            A.regions,
            'variable' AS validity,
            A.name,
            A.desc,
            '' AS mode
FROM        DaysMov A
WHERE       A.mode = ''

Many thanks for any help with this, Tim.

Это было полезно?

Решение

You should be able to do the same thing with an inner join, like this:

SELECT      
        B.calendar_DT AS dayMov,
        A.countries,
        A.regions,
        'variable' AS validity,
        A.name,
        A.desc,
        '' AS mode
FROM    DaysMov A
INNER JOIN Calendar B ON B.year_id = @selYear AND B.month_of_year = A.calMonth AND B.day_of_week = A.calDay AND (B.day_of_month BETWEEN A.calFrom AND A.calTill)
WHERE   A.mode = ''

This query will not produce a row when Calendar does not have a match on the specified condition. Assuming that the query from your post has worked (except that it produced some rows that you did not want) the query above shouldn't produce additional rows, because the subquery on the same condition returned at most a single result.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top