且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在SQL Server中使用自定义PIVOT?如何在SQL服务器中使用PIVOT运算符显示之间和之间的周数?

更新时间:2023-09-22 20:15:46

Quote:

先生,我不知道该怎么做?

sir i don't know what to do in this ?



首先将数据转换为汇总形式:


So start by getting the data into a aggregated form:

SELECT DatePart(ww, Date_of_Joining) AS WeekNo, COUNT(*) AS PerMonth 
FROM tblEmployeeDetails 
GROUP BY DatePart(ww, Date_of_Joining)

这为您提供了所需的信息,没有归零信息,也没有PIVOT。

接下来,添加零信息:这很复杂,最简单的方法是创建一个包含所有周数的表:一列,包含1到53个。

This gives you the info you need, without the zeroed info, and without the PIVOT.
Next, add the zero information: That's complex, and the simplest way to do it is to create a table of all the week numbers: a single column, containing 1 to 53 inclusive.

SELECT w.WeekNo AS WeekNo, COUNT(s.EMPId) AS PerMonth 
FROM tblEmployeeDetails s
RIGHT JOIN dbo.WeekNumbers w ON w.WeekNo = DatePart(ww, s.Date_of_Joining)
WHERE w.WeekNo BETWEEN 1 AND 5
GROUP BY w.WeekNo



现在,您拥有所需的原始数据:


Now, you have the raw data you need:

WeekNo	PerMonth
1	0
2	0
3	2
4	1
5	1

你剩下要做的就是PIVOT了。我会留给你的! :笑:

And all you have left to do is PIVOT that. I'll leave that to you! :laugh:


我会说你在将PIVOT与SQL Server一起使用 [ ^ ]



我希望这对你有用
I'd say you have an almost identical case in the example 3 at Using PIVOT with SQL Server[^]

I hope that is useful for you