分组行,但选择显示组中一个字段的值?

时间:2016-06-22 16:20:47

标签: tsql

我有一个请求,我不确定我可以批准。希望按某些字段对行进行分组,但随后还会显示一个项目描述字段,该字段将分解该组,我无法保证在项目描述字段中使用min()或max()将导致在所有字段中显示所需的描述案例。

请注意,在此代码中,我将项目描述注释掉了,这会给出他们想要的行数和分组数。

SELECT 
    --L.ITEMDESC,
    SUM(L.UNITPRCE) AS Rate,
    SUM(L.XTNDPRCE) AS Price,
    L.QUANTITY AS Quantity,
    RTRIM(L.UOFM) AS UOFM, 
    C.COMMENT_1, 
    C.COMMENT_2, 
    C.COMMENT_3
FROM 
    SOP10200 L, SOP10202 C
WHERE 
    L.SOPNUMBE = C.SOPNUMBE
    AND L.SOPTYPE = C.SOPTYPE
    AND L.LNITMSEQ = C.LNITMSEQ
    AND L.SOPNUMBE = '00644680'
GROUP BY 
    C.COMMENT_1, C.COMMENT_2, C.COMMENT_3, L.QUANTITY, L.UOFM--, L.ITEMDESC

例如交易的结果:

Rate    Price   Quantity    UOFM    COMMENT 1               COMMENT 2   COMMENT 3
0.37891 63.56   167.72421   THERMS  CESeq: 52593^Act^TARGET 10/13/2015  10/31/2015
0.34254 30.23   88.27579    THERMS  CESeq: 52593^Act^TARGET 11/1/2015   11/10/2015

如果我出于解释目的而包含项目描述,则结果如下:

ITEMDESC                Rate    Price   Quantity    UOFM    COMMENT 1               COMMENT 2   COMMENT 3
Gas on the PG&E System  0.34691 58.19   167.72421   THERMS  CESeq: 52593^Act^TARGET 10/13/2015  10/31/2015
PGE SPCC ADDER          0.03200 5.37    167.72421   THERMS  CESeq: 52593^Act^TARGET 10/13/2015  10/31/2015
Gas on the PG&E System  0.31054 27.41   88.27579    THERMS  CESeq: 52593^Act^TARGET 11/1/2015   11/10/2015
PGE SPCC ADDER          0.03200 2.82    88.27579    THERMS  CESeq: 52593^Act^TARGET 11/1/2015   11/10/2015

在这个具有此数据的特定场景中,他们表示希望看到Gas on the PG&E System作为描述,但我不能只使用min()或max()来解决此事务的场景,因为这可能不适合其他

因此,此图像在其中一个表中显示我可以使用单位成本不等于零作为选择要使用哪一行描述的规则。但我正在努力思考如何在代码中实现它。我想向客户提出建议。如何利用单位成本<> 0选择显示哪个项目描述?

Data Options?

2 个答案:

答案 0 :(得分:1)

这是大纲

select * from 
(
select a, b, c, unitcost 
     , sum(UNITPRCE) over (partition by a, b order by 1) as p1 
     , sum(XTNDPRCE) over (partition by a, b order by 1) as p2 
     , row_number()  over (partition by a, b order by unit unitcost) as rn 
) as tt 
where tt.rn = 1

答案 1 :(得分:1)

狗仔队的答案很好。另一种解决方案是执行以下操作:

SELECT 
    Max(case when L.UNITPRCE <> 0 then L.ITEMDESC else null end) AS ITEMDESC,
    SUM(L.UNITPRCE) AS Rate,
    SUM(L.XTNDPRCE) AS Price,
    L.QUANTITY AS Quantity,
    RTRIM(L.UOFM) AS UOFM, 
    C.COMMENT_1, 
    C.COMMENT_2, 
    C.COMMENT_3
FROM 
    SOP10200 L, SOP10202 C
WHERE 
    L.SOPNUMBE = C.SOPNUMBE
    AND L.SOPTYPE = C.SOPTYPE
    AND L.LNITMSEQ = C.LNITMSEQ
    AND L.SOPNUMBE = '00644680'
GROUP BY 
    C.COMMENT_1, C.COMMENT_2, C.COMMENT_3, L.QUANTITY, L.UOFM

如果只有FIRST_VALUEaggregate function instead of an analytic function你可以使用它,但是我们仍然坚持使用这些肮脏的解决方案。