查询中的组数据

时间:2016-10-26 17:19:51

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

我写了这个查询,结果没有被分组。它们看起来像这样:

Facility | Posting Month | Account Type | Amount
-------------------------------------------------
Name     | July          | Debit Adj.   | 100
Name     | July          | Credit Adj.  | -200
Name     | July          | Debit Adj.   | 150
Name     | July          | Credit Adj.  | -150
-------------------------------------------------

我想要获得的结果是借记调整的过帐月份出现一次。和信贷调整类型和各自的总金额。总计250美元的借记和 - 350美元的学分。谢谢您的帮助!

SELECT pw.Facility, DATENAME(mm, pw.[Posting Date]) AS [Posting Month],
     lc.[Gl Account Type], sum(pw.[Tx Amt]) AS Amount
FROM DBO.PaymentWOLedger AS pw
    JOIN DBO.LedgerCodeTable AS lc
      ON lc.[Description] = pw.[Tx Desc]
WHERE lc.[Gl Account Type] = 'Credit Adjustment (Write Off)' OR 
      lc.[GlAccount Type] = 'Debit Adjustment (CWO)'
GROUP BY pw.[Posting Date], pw.Facility, lc.[Gl Account Type]
ORDER BY pw.Facility, pw.[Posting Date]

1 个答案:

答案 0 :(得分:2)

Month&中使用Date代替Group by Order by

GROUP BY DATENAME(mm, pw.[Posting Date]), pw.Facility, lc.[Gl Account Type]
ORDER BY pw.Facility, DATENAME(mm, pw.[Posting Date])

目前,每个date的数据都会被分组,因为您已pw.[Posting Date]使用了Group by date/month/year部分数据。