Sql server Sql查询以获取给定年份每个月按客户类型(1,2,3,4,5)的总付款
我有两张付款和客户表 我们有5种类型的客户1、2、3、4、5 我希望在给定年份的每个月按客户类型1,2,3,4,5获得总付款 如果任何客户类型没有任何付款,则应为0 以下是我目前的查询:-Sql server Sql查询以获取给定年份每个月按客户类型(1,2,3,4,5)的总付款,sql-server,Sql Server,我有两张付款和客户表 我们有5种类型的客户1、2、3、4、5 我希望在给定年份的每个月按客户类型1,2,3,4,5获得总付款 如果任何客户类型没有任何付款,则应为0 以下是我目前的查询:- SELECT "Month" = month(o.PaymentDate) , "Year" = year(o.PaymentDate) , Amount = sum(o.Amoun
SELECT
"Month" = month(o.PaymentDate)
, "Year" = year(o.PaymentDate)
, Amount = sum(o.Amount)
, c.CustomerTypeID
FROM
Payments o
INNER JOIN
Customers c ON o.CustomerID = c.CustomerID
WHERE
o.PaymentDate >= convert(DATETIME, '1/1/2013 12:00:00 AM')
AND o.PaymentDate < convert(DATETIME, '12/31/2013 12:00:00 AM')
GROUP BY
month(o.PaymentDate)
, year(o.PaymentDate)
,c.CustomerTypeID
ORDER BY
year(o.PaymentDate)
, month(o.PaymentDate)
,c.CustomerTypeID
结果是:-
月-年总客户类型ID
1 2013 456 1
1 2013 678 2
1 2013 346 3
1 2013 3245 5
由于目前没有为CustomerType 4提供数据,所以我想在amount列中显示0,月份和年份将相同
有人能帮我吗
提前感谢。使用右外部联接将所有客户和合并金额合并为0,0表示返回0而不是null
SELECT
c.CustomerTypeID
FROM
(SELECT "Month" = month(o.PaymentDate)
, "Year" = year(o.PaymentDate)
, Amount = sum(o.Amount)
, o.CustomerID
FROM Payments o
WHERE
o.PaymentDate >= convert(DATETIME, '1/1/2013 12:00:00 AM')
AND o.PaymentDate < convert(DATETIME, '12/31/2013 12:00:00 AM')
) D
RIGHT OUTER JOIN
Customers c ON o.CustomerID = c.CustomerID
GROUP BY
D.MONTH
, D.YEAR
,c.CustomerTypeID
ORDER BY
D.MONTH
, D.YEAR
,c.CustomerTypeID
当您使用聚合时,您应该认真考虑使用分组,而不是分组:
从-: 如果使用ALL,查询结果将包括GROUP by子句生成的所有组,即使某些组没有符合搜索条件的行。如果没有ALL,则包含GROUP BY的SELECT语句不会显示没有行符合条件的组SELECT
"Month" = month(o.PaymentDate)
, "Year" = year(o.PaymentDate)
, Amount = sum(o.Amount)
, c.CustomerTypeID
FROM
Payments o
INNER JOIN
Customers c ON o.CustomerID = c.CustomerID
WHERE
o.PaymentDate >= convert(DATETIME, '1/1/2013 12:00:00 AM')
AND o.PaymentDate < convert(DATETIME, '12/31/2013 12:00:00 AM')
GROUP BY ALL
month(o.PaymentDate)
, year(o.PaymentDate)
,c.CustomerTypeID
ORDER BY
year(o.PaymentDate)
, month(o.PaymentDate)
,c.CustomerTypeID
谢谢@Amireza,我用右外连接替换了内连接,但结果相同。您可以在这里发布sql查询吗?而且对于客户类型4,它不会返回NULL。它不会带来结果。因为customertype 4没有数据量。但我想将其作为默认值0。我编辑了我的帖子,但我是根据您的查询编写的,可能有点问题。因此,如果它不起作用,那么就接受这个想法并实现它。谢谢@Yosi,但它并没有带来渴望的结果。@AnandMeena-不管怎样,如果你不使用它,它将是一个bug,你需要所有的客户数据……你不应该全部使用group by。从TechNet文章中:GROUP BY ALL将在未来版本的Microsoft SQL Server中删除。避免在新的开发工作中使用GROUP BY ALL,并计划修改当前使用iThanks@Yosi的应用程序,但仍然存在一些问题,因为它返回227行。这些应该是总共60行12个月*每年5种类型。非常感谢@Podiluska,它现在运行良好。你是冠军:-。
SELECT
"Month" = month(o.PaymentDate)
, "Year" = year(o.PaymentDate)
, Amount = sum(o.Amount)
, c.CustomerTypeID
FROM
Payments o
INNER JOIN
Customers c ON o.CustomerID = c.CustomerID
WHERE
o.PaymentDate >= convert(DATETIME, '1/1/2013 12:00:00 AM')
AND o.PaymentDate < convert(DATETIME, '12/31/2013 12:00:00 AM')
GROUP BY ALL
month(o.PaymentDate)
, year(o.PaymentDate)
,c.CustomerTypeID
ORDER BY
year(o.PaymentDate)
, month(o.PaymentDate)
,c.CustomerTypeID