Подзапрос SQL из 2 запросов доступа - PullRequest
0 голосов
/ 14 декабря 2018

У меня есть два запроса, которые я хотел бы объединить в один запрос, используя подзапрос, но я не смог определить правильный синтаксис для создания подзапроса.

Запрос B - это запрос, который должен бытьссылка на запрос A для правильной работы.

Любая помощь будет полезна, так как я только начинаю свое обучение по Transact-SQL.

- эти два запроса переносятся из Access как отдельные запросы -

ЗАПРОС A:

SELECT Shipment.[Shipment Description], Shipment.[Load ID], Shipment.[Origin Name], Shipment.[Origin City], Shipment.[Origin State], Shipment.[Origin Zip], Shipment.[Origin Country], Shipment.[Destination Name], TMS_Shipment.[Destination State], Shipment.[Destination City], Shipment.[Destination Zip], Shipment.[Destination Country], Shipment.[Pickup To Date/Time], Shipment_Container.Pallets, Shipment_Container.Pieces, [QUERY B].[SumOfReference Number] AS 'Original Number of Pieces', Shipment_Container.Length, Shipment_Container.Width, Shipment_Container.Height, Shipment_Container.[Scaled Weight], Shipment_Container.[Stackability Indicator], Month([Shipment].[Pickup To Date/Time]) AS [Month], Year([Shipment].[Pickup To Date/Time]) AS [Year], [Shipment_Container].[Scaled Weight]/42000 AS [Weight Utilization],Round((100/[Width]),0) AS [# Wide], Round(([QUERY B].[SumOfReference Number]/(Round((100/[Width]),0)))/[Shipment_Container].[Stackability Indicator],0) AS [# Long], Load.[Service Code], (((Round(([QUERY B].[SumOfReference Number]/(Round((100/[Width]),0)))/[Shipment_Container].[Stackability Indicator],0))*[Shipment_Container].[Length])/(629*0.85)) AS Cube, Shipment.[Party Responsible for Freight cost], Load.[Number of Stops]
    Into Qry_Utilization
FROM (Load INNER JOIN (Shipment_Container INNER JOIN Shipment ON Shipment_Container.[Shipment Description] = Shipment.[Shipment Description]) ON Load.[Load ID] = Shipment.[Load ID]) INNER JOIN [QUERY B] ON Shipment_Container.[Shipment Description] = [QUERY B].[Shipment Description]
WHERE (((Shipment_Container.Length)>1) AND ((Shipment_Container.Width)>1) AND ((Shipment_Container.Height)>1) AND ((Load.[Service Code])='TL' Or (Load.[Service Code])='SPTL' Or (Load.[Service Code])='SPFB' Or (Load.[Service Code])='TLMR'));

ЗАПРОС B:

(SELECT Shipment_Container_Reference.[Shipment Description], Shipment_Container_Reference.[Reference Type Desc], Sum(Shipment_Container_Reference.[Reference Number]) AS [SumOfReference Number]
FROM Shipment_Container_Reference
GROUP BY Shipment_Container_Reference.[Shipment Description], Shipment_Container_Reference.[Reference Type Desc]
HAVING (((Shipment_Container_Reference.[Reference Type Desc]) Like '*number of pieces*')))

Ответы [ 2 ]

0 голосов
/ 14 декабря 2018

MSAccess, по крайней мере, когда я его использовал, не поддерживал должным образом подзапросы, поэтому вам приходилось делать то, что вы показали;в большинстве случаев преобразование его в SQL это просто вопрос изменения что-то вроде этого

SELECT stuff 
FROM TableA 
INNER JOIN QueryB ON blah

на

SELECT stuff 
FROM TableA 
INNER JOIN (
   SELECT other_stuff 
   FROM TableB 
   WHERE blahB
) AS QueryB ON blah`

Кроме этого

  • вы будетенеобходимо преобразовать любые * подстановочные знаки в % подстановочные знаки
  • , если вы действительно используете MySQL (как подсказывает текущая пометка тегами), вам необходимо заменить разделители полей [ и ] на `(несмещенный ключ ~)
0 голосов
/ 14 декабря 2018

Когда вам нужно выполнить один запрос (в данном случае B), а затем использовать его результаты в другом запросе (в данном случае A), тогда стандарт SQL предлагает вам общее выражение таблицы (CTE).

Inв вашем случае запрос (с CTE) должен иметь форму:

with b as (
  select ... -- all your SQL select here
)
select ... from a join b ... -- note that here you can use any table, as well as B

В вашем случае (добавлено некоторое форматирование):

with b as
(
    SELECT
      Shipment_Container_Reference.[Shipment Description],
      Shipment_Container_Reference.[Reference Type Desc],
      Sum(Shipment_Container_Reference.[Reference Number]) AS [SumOfReference Number]
    FROM Shipment_Container_Reference
    GROUP BY Shipment_Container_Reference.[Shipment Description],
      Shipment_Container_Reference.[Reference Type Desc] HAVING
      (
          (
              (
                  Shipment_Container_Reference.[Reference Type Desc]
              )
              Like '*number of pieces*'
          )
      )
  )
SELECT
  Shipment.[Shipment Description],
  Shipment.[Load ID],
  Shipment.[Origin Name],
  Shipment.[Origin City],
  Shipment.[Origin State],
  Shipment.[Origin Zip],
  Shipment.[Origin Country],
  Shipment.[Destination Name],
  TMS_Shipment.[Destination State],
  Shipment.[Destination City],
  Shipment.[Destination Zip],
  Shipment.[Destination Country],
  Shipment.[Pickup To Date/Time],
  Shipment_Container.Pallets,
  Shipment_Container.Pieces,
  [QUERY B].[SumOfReference Number] AS 'Original Number of Pieces',
  Shipment_Container.Length,
  Shipment_Container.Width,
  Shipment_Container.Height,
  Shipment_Container.[Scaled Weight],
  Shipment_Container.[Stackability Indicator],
  Month([Shipment].[Pickup To Date/Time]) AS [Month],
  Year([Shipment].[Pickup To Date/Time]) AS [Year],
  [Shipment_Container].[Scaled Weight]/42000 AS [Weight Utilization],
  Round((100/[Width]),0) AS [# Wide],
  Round(([QUERY B].[SumOfReference Number]/(Round((100/[Width]),0)))/[Shipment_Container].[Stackability Indicator],0) AS [# Long],
  Load.[Service Code],
  (((Round(([QUERY B].[SumOfReference Number]/(Round((100/[Width]),0)))/[Shipment_Container].[Stackability Indicator],0))*[Shipment_Container].[Length])/(629*0.85)) AS Cube,
  Shipment.[Party Responsible for Freight cost],
  Load.[Number of Stops] Into Qry_Utilization
FROM
  (
      Load
      INNER JOIN
      (
          Shipment_Container
          INNER JOIN Shipment ON Shipment_Container.[Shipment Description] = Shipment.[Shipment Description]
      )
      ON Load.[Load ID] = Shipment.[Load ID]
  )
  INNER JOIN [QUERY B] ON Shipment_Container.[Shipment Description] = [QUERY B].[Shipment Description]
WHERE
  (
      ((Shipment_Container.Length)>1)
      AND ((Shipment_Container.Width)>1)
      AND ((Shipment_Container.Height)>1)
      AND
      (
          (
              Load.[Service Code]
          )
          ='TL' Or
          (
              Load.[Service Code]
          )
          ='SPTL' Or (Load.[Service Code])='SPFB' Or (Load.[Service Code])='TLMR'
      )
  )
  ;

Обратите внимание, что этот запрос не на 100%правильно в Transact-SQL, поскольку он все еще имеет некоторые причуды MS-Access (нестандартные).

...