复杂查询SQL

时间:2017-08-08 08:03:17

标签: sql sql-server

我目前正在进行sql查询,我在三个不同的行中接收数据,我真的需要一行中的数据

SELECT
substring(D.F1056, patindex('%[^0]%',D.F1056), 10) as Shop_Number,
REPLACE(CONVERT(VARCHAR(10), D.F254, 103), '/', '') AS Todays_Date,
SDP_TAB.F03  as Rayon,
[SDP_TAB].F04 as Famille,
CASE 
WHEN D.F1034=3 THEN SUM(D.F64) 
                            ELSE 0 
END as Qty_Sold ,
CASE 
WHEN D.F1034=3 THEN convert(DOUBLE PRECISION, SUM(D.F65)*100) * 10
                            ELSE 0 
END as chiffre_daffaire_Caisse,
0 as montant_remisse_caisse,
CASE
WHEN D.F1034=3011 THEN SUM(D.F64) 
WHEN D.F1034=3012 THEN SUM(D.F64) 
                            ELSE 0 
END as Qty_retour,
CASE
WHEN D.F1034=3011 THEN SUM(D.F65) 
WHEN D.F1034=3012 THEN SUM(D.F65) 
                            ELSE 0 
END as Montant_Retour,
0 as Quantity,
CASE
WHEN D.F1034=3102 THEN SUM(D.F64) 
                            ELSE 0 
END as ClientCount,
F1034
FROM 
            [dbo].[RPT_ITM_D] D
            LEFT OUTER JOIN [dbo].[POS_TAB] ON (D.F01=POS_TAB.F01)
            LEFT OUTER JOIN [dbo].SDP_TAB ON (POS_TAB.F04=SDP_TAB.F04)

where 
            D.F1034 IN (3,3012,3011,3102)
            AND
            D.F254 = convert(varchar, getdate(), 101)     
group by D.F1056,D.F254,SDP_TAB.F03,SDP_TAB.F04,D.F1034

我的数据正在填充如下Populated Data

我有三行,因为我对F1034字段有几个条件

有没有办法让预期结果低于enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个。 (将max与计算列一起使用)

With  resultData as (

—Put your original query here

 )
Select Shop_Number, Todays_Date,rayon,famille
,max(Qty_Sold) Qty_Sold, max(chiffre_daffaire_Caisse) chiffre_daffaire_Caisse
,max(montant_remisse_caisse) montant_remisse_caisse,max(Qty_retour) Qty_retour,max(Montant_Retour) Montant_Retour
,max(Quantity)Quantity,max(ClientCount) ClientCount,max(F1034) F1034
From resultData 
group by Shop_Number, Todays_Date,rayon,famille