在SQL中编写sum,但在GROUP By中编写其他列

时间:2016-08-10 15:17:13

标签: sql sql-server sql-server-2014

我的一个列属性中有一个总和。但其余的我必须分组。但这是对的吗?或者你可以用其他方式做到吗?

我有这个:

function getRandomQuote() {
    return arrayQ[Math.floor(Math.random() * arrayQ.length)];
};

谢谢

但我得到这个作为输出:

SELECT 
    SU.[Vendor No_] as LeveranciersNR, V.Name as LeveranciersName, 
    SU.[Item No_], SU.[Reorder Cycle] as bestelfrequentie,
    SU.[Location Code], SU.[Reordering Policy], 
    I.Description as procuctOmschrijving,
    SUM(VLE.[Purchase (LCY)]) as Inkoopomzet
FROM 
    [Verploegen POC$Vendor] V
JOIN
    [Verploegen POC$Vendor Ledger Entry] VLE ON VLE.[Vendor No_] = V.No_
JOIN 
    [Verploegen POC$Stockkeeping Unit] SU ON V.No_ = SU.[Vendor No_]
JOIN 
    [Verploegen POC$Item] I ON I.No_ = SU.[Item No_]
WHERE 
    SU.[Reordering Policy] = 2 
    AND VLE.[Posting Date] BETWEEN '2016-01-01' AND '2016-12-31'
GROUP BY 
    VLE.[Vendor No_], SU.[Vendor No_], V.Name, SU.[Item No_], 
    SU.[Reorder Cycle], SU.[Location Code], SU.[Reordering Policy],
    I.Description
ORDER BY 
    SU.[Location Code]

2 个答案:

答案 0 :(得分:0)

这是具有较少分组的脚本,但它应该返回相同的结果,并且没有事实它会更快地工作。

;WITH VLE as (
    SELECT SUM([Purchase (LCY)]) as Inkoopomzet, [Vendor No_] 
    FROM [Verploegen POC$Vendor Ledger Entry]
    WHERE [Posting Date] BETWEEN '2016-01-01' AND '2016-12-31'
    GROUP BY [Vendor No_]
)
SELECT 
    SU.[Vendor No_] as LeveranciersNR, V.Name as LeveranciersName, 
    SU.[Item No_], SU.[Reorder Cycle] as bestelfrequentie,
    SU.[Location Code], SU.[Reordering Policy], 
    I.Description as procuctOmschrijving,
    VLE.Inkoopomzet
FROM [Verploegen POC$Vendor] AS V
INNER JOIN VLE ON VLE.[Vendor No_] = V.No_
INNER JOIN [Verploegen POC$Stockkeeping Unit] SU ON V.No_ = SU.[Vendor No_]
INNER JOIN [Verploegen POC$Item] I ON I.No_ = SU.[Item No_]
WHERE SU.[Reordering Policy] = 2 
ORDER BY SU.[Location Code];

答案 1 :(得分:0)

由于您正在进行内部联接,为什么不将where子句标准移动到相应的联接中。它应该运行得更快,因为连接将创建更小的结果集:

SELECT 
    SU.[Vendor No_] as LeveranciersNR, V.Name as LeveranciersName, 
    SU.[Item No_], SU.[Reorder Cycle] as bestelfrequentie,
    SU.[Location Code], SU.[Reordering Policy], 
    I.Description as procuctOmschrijving,
    SUM(VLE.[Purchase (LCY)]) as Inkoopomzet
FROM 
    [Verploegen POC$Vendor] V
JOIN
    [Verploegen POC$Vendor Ledger Entry] VLE ON VLE.[Vendor No_] = V.No_
    AND VLE.[Posting Date] BETWEEN '2016-01-01' AND '2016-12-31'
JOIN 
    [Verploegen POC$Stockkeeping Unit] SU ON V.No_ = SU.[Vendor No_]
    AND SU.[Reordering Policy] = 2 
JOIN 
    [Verploegen POC$Item] I ON I.No_ = SU.[Item No_]
GROUP BY 
    VLE.[Vendor No_], SU.[Vendor No_], V.Name, SU.[Item No_], 
    SU.[Reorder Cycle], SU.[Location Code], SU.[Reordering Policy],
    I.Description
ORDER BY 
    SU.[Location Code]