我有以下查询
select a.EmpId,AttenDate,status
from dbo.Attendance as a
inner join dbo.employeemast as e
on a.empid=e.empid
where e.EmpWeekOfType='V'`
它给了我:
1500011 2014-08-31 00:00:00.000 A
1500011 2014-09-01 00:00:00.000 A
1500011 2014-09-02 00:00:00.000 A
1500011 2014-09-03 00:00:00.000 A
1500011 2014-09-04 00:00:00.000 A
1500011 2014-09-05 00:00:00.000 A
1500011 2014-09-06 00:00:00.000 P
1500011 2014-09-07 00:00:00.000 A
1500011 2014-09-08 00:00:00.000 A
1500011 2014-09-09 00:00:00.000 A
1500011 2014-09-10 00:00:00.000 A
1500011 2014-09-11 00:00:00.000 A
我想用这种格式排列行:
150011 | 2014-08-31 00:00:00.000|2014-09-01 00:00:00.000|2014-09-02 00:00:00.000....
A | A ........
请建议我查询??
答案 0 :(得分:0)
如果我理解正确,你想将基于行的格式(这是RDBMS和SQL使用的格式)转换为基于列的格式吗?
这是不可能的(使用标准SQL - 可能有特定于供应商的扩展,这将使其更容易,但您没有指定ans供应商)。原因,这是不可能的,具有RDBMS和SQL的性质,其中列需要很好地定义,而行数取决于数据。
此外,您还尝试在每列的一列中存储不同的数据类型。而是使用SQL输出并使用您选择的编程语言将其转换为您需要的内容。
答案 1 :(得分:0)
至少接近你的目标的解决方案是使用数组(至少在Postgre中):
SELECT a.EmpId, array_agg(AttenDate), array_agg(status)
FROM dbo.Attendance AS a
INNER JOIN dbo.employeemast AS e
ON a.empid=e.empid
WHERE e.EmpWeekOfType='V'
GROUP BY a.EmpId;
很抱歉,但不知道任何类似的MS-SQL或MySQL。然而,正如彼得所说,完全按照你的意愿获得输出是不可能的。
答案 2 :(得分:0)
DECLARE @Temp VARCHAR(MAX)
select @Temp=ISNULL(@Temp+' | ','')+CAST(a.EmpId AS VARCHAR)+' '+CAST(AttenDate AS VARCHAR)+' '+[status]
from dbo.Attendance as a
inner join dbo.employeemast as e
on a.empid=e.empid
where e.EmpWeekOfType='V'
SELECT @Temp
答案 3 :(得分:0)
这可能会对您有所帮助,此代码位于MS SQL SERVER中:
DECLARE @Columns VARCHAR(max)
SELECT @Columns = Stuff((SELECT ',' + '[' + CONVERT(VARCHAR(30), AttenDate, 121)
+ ']'
FROM Attendance s
WHERE s.empid = t.empid
FOR XML PATH('')), 1, 1, '')
FROM Attendance AS t
GROUP BY t.empid
DECLARE @sql NVARCHAR(max)= 'select [empid],' + @Columns
+ ' from Attendance pivot
(max(stus)
FOR AttenDate in(' + @Columns + ')
)as pvt'
EXEC sp_executesql
@sql
并且根据您的查询,这将是:
IF OBJECT_ID('tempdb..#Attendance',N'U') IS NOT NULL
DROP TABLE #Attendance
SELECT a.EmpId,
AttenDate,
status
INTO #Attendance
FROM dbo.Attendance AS a
INNER JOIN dbo.employeemast AS e
ON a.empid = e.empid
WHERE e.EmpWeekOfType = 'V'
DECLARE @Columns VARCHAR(max)
SELECT @Columns = Stuff((SELECT ',' + '[' + CONVERT(VARCHAR(30), AttenDate, 121)
+ ']'
FROM #Attendance s
WHERE s.empid = t.empid
FOR XML PATH('')), 1, 1, '')
FROM #Attendance AS t
GROUP BY t.empid
DECLARE @sql NVARCHAR(max)= 'select [empid],' + @Columns
+ ' from #Attendance pivot
(max(stus)
FOR AttenDate in(' + @Columns + ')
)as pvt'
EXEC sp_executesql
@sql
我从here获取了参考资料。
答案 4 :(得分:0)
尝试使用游标获取每一行,从行获取empid并附加到变量(empid一次和连续行datetime字段,直到empid发生更改)。将变量存储在临时表中。对每一行执行此操作并将数据附加到变量,直到employeeid发生更改。最后从临时表中选择.....获取结果的方法。