AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 262177
Accepted
VansFannel
VansFannel
Asked: 2020-03-19 00:59:03 +0800 CST2020-03-19 00:59:03 +0800 CST 2020-03-19 00:59:03 +0800 CST

Junte três consultas em uma

  • 772

Estou usando o SQL Server 13.0.5102.14.

Eu tenho essas três tabelas:

CREATE TABLE [dbo].[ProductionOrder]
(
    [ProductionOrderId] INT NOT NULL IDENTITY (1, 1), 
    [ProductId] INT NOT NULL, 
    [Name] NVARCHAR(50) NOT NULL,
    CONSTRAINT [PK_ProductionOrder] PRIMARY KEY CLUSTERED 
    (
        [ProductionOrderId] ASC
    ))
)

CREATE TABLE [dbo].[Code]
(
    [CodeId] int NOT NULL IDENTITY(1, 1),
    [Serial] [varchar](38) not null,
    [ProductionOrderId] int NOT NULL,
    [AggregationLevel] [tinyint] NOT NULL,
     CONSTRAINT [PK_Code] PRIMARY KEY CLUSTERED 
    (
        [CodeId] ASC
    ),
    CONSTRAINT [UC_Code_Serial] UNIQUE ([Serial]),
    CONSTRAINT [FK_Code_ProductionOrder_ProductionOrderId] FOREIGN KEY ([ProductionOrderId]) REFERENCES [dbo].[ProductionOrder] ([ProductionOrderId]))
)

CREATE TABLE [dbo].[VariableData]
(
    [ProductionOrderId] INT NOT NULL,
    [AggregationLevelConfigurationId] TINYINT NOT NULL, 
    [VariableDataId] VARCHAR(4) NOT NULL, 
    [Value] NVARCHAR(200) NOT NULL,
    CONSTRAINT [PK_VariableData] PRIMARY KEY CLUSTERED 
    (
        [AggregationLevelConfigurationId] ASC,
        [ProductionOrderId] ASC,
        [VariableDataId] ASC
    ), 
    CONSTRAINT [FK_VariableData_AggregationLevelConfiguration_AggregationLevelConfigurationId] FOREIGN KEY ([AggregationLevelConfigurationId], [ProductionOrderId]) REFERENCES [dbo].[AggregationLevelConfiguration] ([AggregationLevelConfigurationId], [ProductionOrderId]) ON DELETE CASCADE,
    CONSTRAINT [FK_VariableData_ProductionOrder_ProductionOrderId] FOREIGN KEY ([ProductionOrderId]) REFERENCES [dbo].[ProductionOrder] ([ProductionOrderId]),
    CONSTRAINT [CK_VariableData_VariableDataId] CHECK (([VariableDataId]<>N''))
)

CREATE TABLE [dbo].[Product]
(
    [ProductId] INT NOT NULL IDENTITY (1, 1),
    [ProductCode] VARCHAR(14) not null,
    [Description] NVARCHAR(50) NULL,
    [LawId] TINYINT NOT NULL,  
    [Name] NVARCHAR(100) NOT NULL, 
    [Comment] NVARCHAR(100) NULL, 
    CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED 
    (
        [ProductId] ASC
    ),
    CONSTRAINT [CK_Product_ProductCode] CHECK (([ProductCode]<>N'')),
    CONSTRAINT [CK_Product_Name] CHECK (([Name]<>N''))
)

CREATE TABLE [dbo].[AggregationChildren]
(
    [AggregationChildrenId] INT NOT NULL,
    [AggregationId] INT NOT NULL,
    [Position] [int] NOT NULL,
    CONSTRAINT [PK_AggregationChildren] PRIMARY KEY CLUSTERED 
    (
        [AggregationChildrenId] ASC
    ), 
    CONSTRAINT [FK_AggregationChildren_Aggregation_AggregationId] FOREIGN KEY ([AggregationId]) REFERENCES [Aggregation]([AggregationId]) ON DELETE CASCADE, 
    CONSTRAINT [FK_AggregationChildren_Code_AggregationChildrenId] FOREIGN KEY ([AggregationChildrenId]) REFERENCES [Code]([CodeId])
)

CREATE TABLE [dbo].[Aggregation]
(
    [AggregationId] INT NOT NULL,
    [Created] varchar(34) NULL,
    CONSTRAINT [PK_Aggregation] PRIMARY KEY CLUSTERED
    (
        [AggregationId] ASC
    ),
    CONSTRAINT [FK_Aggregation_Code_AggregationId] FOREIGN KEY ([AggregationId]) REFERENCES [dbo].[Code] ([CodeId])
)

Eu tenho essas três consultas de trabalho :

declare @prodID int = 1;
declare @lotAI varchar(4) = '10';

select cod.Serial as ItemNO
     , varData.Value as Lot
     , pro.ProductCode as Product

  from dbo.VariableData varData 
        JOIN dbo.Code cod ON varData.ProductionOrderId = cod.ProductionOrderId
        JOIN dbo.ProductionOrder proOrd ON varData.ProductionOrderId = proOrd.ProductionOrderId
        JOIN dbo.Product pro on proOrd.ProductId = pro.ProductId   

 where varData.ProductionOrderId = @prodID and
       varData.VariableDataId = @lotAI and
       varData.AggregationLevelConfigurationId = 1 and
       cod.AggregationLevel = 1


select cod.Serial as Box

  from dbo.Code cod
       LEFT JOIN dbo.AggregationChildren agg on agg.AggregationId = cod.CodeId

 where cod.ProductionOrderId = @prodID and
       cod.AggregationLevel = 2


select cod.Serial as Pallet

  from dbo.Code cod
       JOIN dbo.Aggregation agg on agg.AggregationId = cod.CodeId

 where cod.ProductionOrderId = @prodID and
       cod.AggregationLevel = 3

Eu quero juntar todos eles em uma consulta. Meu problema para fazer isso é que estou usando dbo.Codepara obter três valores diferentes:

  • select cod.Serial as ItemNO
  • select cod.Serial as Box
  • select cod.Serial as Pallet

Como posso juntar essas três consultas em uma?

sql-server
  • 1 1 respostas
  • 50 Views

1 respostas

  • Voted
  1. Best Answer
    Scott Hodgin - Retired
    2020-03-19T01:38:23+08:002020-03-19T01:38:23+08:00

    Você deve ser capaz de inline o selectsfor Boxe Palletcomo este exemplo mostra:

    DECLARE @prodID INT = 1;
    DECLARE @lotAI VARCHAR(4) = '10';
    
    SELECT cod.Serial AS ItemNO
        ,varData.Value AS Lot
        ,pro.ProductCode AS Product
        ,(
            SELECT cod.Serial AS Box
            FROM dbo.Code cod
            LEFT JOIN dbo.AggregationChildren agg ON agg.AggregationId = cod.CodeId
            WHERE cod.ProductionOrderId = @prodID
                AND cod.AggregationLevel = 2
            ) AS Box
        ,(
            SELECT cod.Serial AS Pallet
            FROM dbo.Code cod
            JOIN dbo.Aggregation agg ON agg.AggregationId = cod.CodeId
            WHERE cod.ProductionOrderId = @prodID
                AND cod.AggregationLevel = 3
            ) AS Pallet
    FROM dbo.VariableData varData
    JOIN dbo.Code cod ON varData.ProductionOrderId = cod.ProductionOrderId
    JOIN dbo.ProductionOrder proOrd ON varData.ProductionOrderId = proOrd.ProductionOrderId
    JOIN dbo.Product pro ON proOrd.ProductId = pro.ProductId
    WHERE varData.ProductionOrderId = @prodID
        AND varData.VariableDataId = @lotAI
        AND varData.AggregationLevelConfigurationId = 1
        AND cod.AggregationLevel = 1
    
    • 1

relate perguntas

  • SQL Server - Como as páginas de dados são armazenadas ao usar um índice clusterizado

  • Preciso de índices separados para cada tipo de consulta ou um índice de várias colunas funcionará?

  • Quando devo usar uma restrição exclusiva em vez de um índice exclusivo?

  • Quais são as principais causas de deadlocks e podem ser evitadas?

  • Como determinar se um Índice é necessário ou necessário

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve