基于基值的带子查询的SQL查询

时间:2018-08-02 14:14:07

标签: sql sql-server subquery

早上好;我有两个试图与子查询一起开发单个查询的表,如果有人可以提供帮助,则会遇到问题。

第一张表-[MPA_Desc]-例如,我解析了更多数据

MPAID Color Model Side
  1    085   x1    R
  2    777   x1    R
  3    085   x1    L
  4    777   x1    L

第二张表-[绘制图表]-例如,我解析了更多数据

Lot  MPAID Amount
 1    1     100
 2    2     250
 3    4     100
 4    2     100

我正试图将其作为查询结果:

Color   R      L
 085   100     0
 777   350    100

这是我正在使用的查询和子查询,它不完整,并且其中没有“ LH”计算,因为我想首先正确获得RH:

Select distinct(mp.Color), rh.RH
from MPA_Desc MP
right join (Select MPA_Desc.MPAID, MPA_Desc.Color, nullif(sum(qty),0) as RH from PaintSched inner join MPA_Desc on PaintSched.MPAID = MPA_Desc.MPAID 
where side = 'r' group by MPA_Desc.MPAID,MPA_Desc.Color) RH
ON mp.MPAID = rh.MPAID
 where Model = 'x1'

但是,这给了我以下结果:

Color    R     
085     100
085     NULL
777     350
777     Null

我知道这是从我的完全联接中获得的,但是我需要将Null显示为“ 0”,我认为nullif可以工作,但显然不能在子查询中使用。其次,我需要它仅在原始查询中按型号显示颜色代码列表,并根据RH或LH零件分开总和。任何帮助都会很棒,谢谢大家!

3 个答案:

答案 0 :(得分:3)

您可以使用PIVOT

DECLARE @MPA_Desc TABLE (MPAID INT, Color VARCHAR(5),  Model VARCHAR(5), Side VARCHAR(5))
INSERT INTO @MPA_Desc VALUES
(1 , '085', 'x1', 'R'),
(2 , '777', 'x1', 'R'),
(3 , '085', 'x1', 'L'),
(4 , '777', 'x1', 'L')

DECLARE @Paintsched TABLE (Lot INT, MPAID INT,  Amount INT)
INSERT INTO @Paintsched VALUES
(1 ,1 , 100),
(2 ,2 , 250),
(3 ,4 , 100),
(4 ,2 , 100)

SELECT Color, ISNULL(R,0) R, ISNULL( L,0) L FROM 
    ( SELECT Color, Side, Amount FROM @MPA_Desc D
        INNER JOIN @Paintsched P ON D.MPAID = P.MPAID ) SRC
        PIVOT (SUM(Amount) FOR Side IN ([R],[L])) PVT

结果:

Color R           L
----- ----------- -----------
085   100         0
777   350         100

答案 1 :(得分:1)

您需要条件聚合:

select md.Color, 
       sum(case when Side = 'R' then ps.amount else 0 end),
       sum(case when Side = 'L' then ps.amount else 0 end)
from MPA_Desc md inner join
     Paintsched ps
     on ps.MPAID = md.MPAID
group by md.Color; 

答案 2 :(得分:1)

尝试以下操作(它是动态的)-:

Declare @sql varchar(MAX),@query nvarchar(MAX)
select @sql=stuff((select  distinct ', sum(case when side='''+side+''' then amount else 0 end) as '+side from [MPA_Desc] FOR XML PATH ('')), 1, 1, '' )
set @query='select color,'+@sql+' from [MPA_Desc] m join [Paintsched] n on m.MPAID=n.MPAID group by color'
EXEC sp_sqlexec @query

SQL Server 2014