我有一个看起来像这样的桌子
EmployeeID | Name | Check Date | Check Num | Check Amount | Quarter
1 | Test | 01/21/2018 | 001231312 | 500 | 1
1 | Test | 03/01/2018 | 001233210 | 100 | 1
1 | Test | 05/01/2018 | 123213321 | 13 | 2
1 | Test | 08/01/2018 | 321909900 | 321 | 3
1 | Test | 12/01/2018 | 321000132 | 123 |4
我需要显示以下输出
EmployeeID | Name | 1st Quarter Date | 1st Quarter Check Num | 1st Quarter Check Amount | 2nd Quarter Date | 2nd Quarter Check Num | 2nd Quarter Check Amount | 3rd Quarter Date | 3rd Quarter Check Num | 3rd Quarter Check Amount | 4th Quarter Date | 4th Quarter Check Num | 4th Quarter Check Amount
我正在对此进行研究,发现了有关使用Pivot的信息,但是尚不清楚何时显示详细信息而不是一些列的汇总。
谢谢
答案 0 :(得分:2)
我认为最简单的方法是将Datepart(QUARTER,Check Date)与案例声明结合使用。
示例:
Select EmployeeID
, Name
, CASE WHEN Datepart(QUARTER, CheckDate) = 1 Then 'Check Date' END AS '1st Quarter Date'
, CASE WHEN Datepart(QUARTER, CheckDate) = 1 Then 'Check Num' END AS '1st Quarter Check Num'
, CASE WHEN Datepart(QUARTER, CheckDate) = 1 Then 'Check Amount' END AS '1st Quarter Check Amount'
, CASE WHEN Datepart(QUARTER, CheckDate) = 2 Then 'Check Date' END AS '2nd Quarter Date'
, CASE WHEN Datepart(QUARTER, CheckDate) = 2 Then 'Check Num' END AS '2nd Quarter Check Num'
, CASE WHEN Datepart(QUARTER, CheckDate) = 2 Then 'Check Amount' END AS '2nd Quarter Check Amount'
, CASE WHEN Datepart(QUARTER, CheckDate) = 3 Then 'Check Date' END AS '3rd Quarter Date'
, CASE WHEN Datepart(QUARTER, CheckDate) = 3 Then 'Check Num' END AS '3rd Quarter Check Num'
, CASE WHEN Datepart(QUARTER, CheckDate) = 3 Then 'Check Amount' END AS '3rd Quarter Check Amount'
, CASE WHEN Datepart(QUARTER, CheckDate) = 4 Then 'Check Date' END AS '4th Quarter Date'
, CASE WHEN Datepart(QUARTER, CheckDate) = 4 Then 'Check Num' END AS '4th Quarter Check Num'
, CASE WHEN Datepart(QUARTER, CheckDate) = 4 Then 'Check Amount' END AS '4th Quarter Check Amount'
From YourTableName
我敢肯定,有更清洁的方法可以做到这一点,而且我敢肯定,其他人也会喜欢。 另外,请不要因为我没有在Datepart中使用相同的列名,我相信由于空格(Datepart(QUARTER,'Check Date'))您将需要''。
编辑:OP添加了一些示例数据,由于有一个“季度”列,我们可以将Case语句更改为:
CASE WHEN QUARTER = 1 Then ....
CASE WHEN QUARTER = 2 Then ....
CASE WHEN QUARTER = 3 Then ....
CASE WHEN QUARTER = 4 Then ....