Получение неверной ошибки столбца из SQL Server при использовании представления - PullRequest
0 голосов
/ 13 октября 2018

Я получаю следующую ошибку:

Сообщение 207, Уровень 16, Состояние 1, Строка 3
Неверное имя столбца 'naicscode'

Задачапод рукой запрашивает таблицу с именем Xyzfirms201701 и получает следующий результат в ответ.

 area    sizeclassep    Number of worksites    employment in size class 
 -----------------------------------------------------------------------
 000000      01               46673                       48975
 000000      02               32105                       54111

Я использую следующий код, чтобы попытаться произвести это:

;WITH sizeclasseptable AS 
(
    SELECT 
        area, naicscode, ownership, sizeclassep 
    FROM 
        (SELECT '01' AS sizeclassep, '50' AS ownership
         UNION SELECT '02' AS sizeclassep, '50' AS ownership
         UNION SELECT '03' AS sizeclassep, '50' AS ownership
         UNION SELECT '04' AS sizeclassep, '50' AS ownership
         UNION SELECT '05' AS sizeclassep, '50' AS ownership
         UNION SELECT '06' AS sizeclassep, '50' AS ownership
         UNION SELECT '07' AS sizeclassep, '50' AS ownership
         UNION SELECT '08' AS sizeclassep, '50' AS ownership
         UNION SELECT '09' AS sizeclassep, '50' AS ownership) t0
    CROSS JOIN 
        (SELECT DISTINCT area FROM xyzfirms201701) t1
)
SELECT
    '000000' AS area,
    t2.[SizeClassep],
    COUNT(*) AS [Number of Worksites],
    SUM(t2.Employment) AS [Employment In Size Class]
FROM
    sizeclasseptable
LEFT JOIN 
    xyzfirms201701 t2 ON t2.area = sizeclasseptable.area 
                      AND t2.naicscode = sizeclasseptable.naicscode
                      AND t2.ownership = sizeclasseptable.ownership
WHERE 
    t2.naicscode LIKE '11%' OR t2.naicscode LIKE '21%'
GROUP BY
    [t2.SizeClassep]
ORDER BY
    [t2.SizeClassep];

Цель первого раздела - заставить SQL производить вывод, даже если данные это делают.не существует.Например, размер classep = 09 будет временами не существовать.Это представляет компанию, которая нанимает 1000 или более в данной отрасли (naicscode).Любые идеи относительно того, почему я получаю неверную ошибку столбца?

Ответы [ 3 ]

0 голосов
/ 13 октября 2018

Вам просто нужно добавить naicscode в подзапросе перекрестного соединения, поскольку он отсутствует в CTE, поэтому вы получаете ошибку Invalid column name.Просто обновите строку ниже, так как я считаю, naicscode является частью таблицы xyzfirms201701.

cross join ( select distinct area, naicscode from xyzfirms201701 ) t1

Обновление Окончательный запрос с использованием псевдонима к таблице CTE.

;with sizeclasseptable as 
(
select t1.area,
       t1.naicscode,
       t0.ownership,
       t0.sizeclassep 
from (
select '01' as sizeclassep, '50' as ownership
union select '02' as sizeclassep, '50' as ownership
union select '03' as sizeclassep, '50' as ownership
union select '04' as sizeclassep, '50' as ownership
union select '05' as sizeclassep, '50' as ownership
union select '06' as sizeclassep, '50' as ownership
union select '07' as sizeclassep, '50' as ownership
union select '08' as sizeclassep, '50' as ownership
union select '09' as sizeclassep, '50' as ownership) t0
cross join ( select distinct area, naicscode from xyzfirms201701 ) t1
)
SELECT
  '000000' AS area,
  sc.[SizeClassep],
  COUNT(*) AS [Number of Worksites],
  SUM(t2.Employment) AS [Employment In Size Class]
from sizeclasseptable sc
left join xyzfirms201701 t2 
  on t2.area=sc.area 
    and t2.naicscode=sc.naicscode
    and t2.ownership=sc.ownership
WHERE t2.naicscode like '11%' or t2.naicscode like '21%'
GROUP BY [sc.SizeClassep]
ORDER BY [sc.SizeClassep];
0 голосов
/ 15 октября 2018

Код ниже дает правильный ответ и без ошибок.Основная проблема заключается в том, что naicscode не определен в CTE и поэтому должен быть исключен.Поскольку его нет в CTE, его необходимо удалить из объединения.Если бы я остановился там, я бы не получил ошибок, но приведенные значения были неправильными.Они были в 9 раз больше, чем должны быть.305 рабочих мест было правильным числом, но ему было дано 2745 и так далее.Отсюда добавление «и t2.sizeclassep = sizeclasseptable.sizeclassep» к оператору соединения не дает 305 результатов на sizeclassep.

;with sizeclasseptable as 
(
select area,ownership,sizeclassep from (
select '01' as sizeclassep, '50' as ownership
union select '02' as sizeclassep, '50' as ownership
union select '03' as sizeclassep, '50' as ownership
union select '04' as sizeclassep, '50' as ownership
union select '05' as sizeclassep, '50' as ownership
union select '06' as sizeclassep, '50' as ownership
union select '07' as sizeclassep, '50' as ownership
union select '08' as sizeclassep, '50' as ownership
union select '09' as sizeclassep, '50' as ownership) t0
cross join ( select distinct area from xyzfirms201701 ) t1
)

 SELECT
'000000' AS area,
t2.[SizeClassep],
COUNT(*) AS [Number of Worksites],
SUM(t2.Employment) AS [Employment In Size Class]
from sizeclasseptable
left join xyzfirms201701 t2 
on t2.area=sizeclasseptable.area 
and t2.ownership=sizeclasseptable.ownership
and t2.sizeclassep = sizeclasseptable.sizeclassep
WHERE t2.naicscode like '11%' or t2.naicscode like '21%'
GROUP BY
t2.SizeClassep
ORDER BY
t2.SizeClassep
0 голосов
/ 13 октября 2018

Откуда вы получаете поле naiscode от?

 ;with sizeclasseptable as (
    select area,ownership,sizeclassep 
    from (
        select '01' as sizeclassep, '50' as ownership
        union select '02' as sizeclassep, '50' as ownership
        union select '03' as sizeclassep, '50' as ownership
        union select '04' as sizeclassep, '50' as ownership
        union select '05' as sizeclassep, '50' as ownership
        union select '06' as sizeclassep, '50' as ownership
        union select '07' as sizeclassep, '50' as ownership
        union select '08' as sizeclassep, '50' as ownership
        union select '09' as sizeclassep, '50' as ownership
    ) t0
    cross join ( 
        select distinct area from xyzfirms201701 
    ) t1
)
SELECT
    '000000' AS area,
    t2.[SizeClassep],
    COUNT(*) AS [Number of Worksites],
    SUM(t2.Employment) AS [Employment In Size Class]
FROM sizeclasseptable
LEFT JOIN xyzfirms201701 t2 ON t2.area=sizeclasseptable.area 
    --AND t2.naicscode=sizeclasseptable.naicscode
    AND t2.ownership=sizeclasseptable.ownership
WHERE t2.naicscode LIKE '11%' OR t2.naicscode LIKE '21%'
GROUP BY [t2.SizeClassep]
ORDER BY [t2.SizeClassep];

Как насчет удаления naicscode из CTE, поскольку оно определенно находится в таблице xyzfirms201701.

...