我的查询透视图遇到一些麻烦:
SELECT *
FROM
(
SELECT [usuario],
[codtrab],
[tna],
[hora],
[tipo],
[fecha]
FROM prueba
) AS SourceTable PIVOT(AVG([tna]) FOR [tipo] IN([entrada], [salida])) AS PivotTable
这将返回一个表
usuario | codtrab | hora fecha entrada salida
name1 | 600 | 08:02:00.0000000 2019-05-17 0 NULL
name1 | 600 | 16:02:00.0000000 2019-05-17 NULL 1
name2 | 200 | 08:10:00.0000000 2019-05-17 0 NULL
name2 | 200 | 16:10:00.0000000 2019-05-17 NULL 1
name3 | 400 | 08:20:00.0000000 2019-05-17 0 NULL
name3 | 400 | 16:20:00.0000000 2019-05-17 NULL 1
我想将数据显示在这样的表中:
usuario codtrab hora fecha entrada salida
name1 600 08:02:00.0000000 2019-05-17 0 1
name2 200 08:10:00.0000000 2019-05-17 0 1
name3 400 08:20:00.0000000 2019-05-17 0 1
答案 0 :(得分:2)
从选择中删除列[hora]后,您可以尝试吗?由于此列具有类似“ Name1”之类的名称的多个值,因此我认为这会创建双行。
SELECT *
FROM
(
SELECT [usuario],
[codtrab],
[tna],
--[hora],
[tipo],
[fecha]
FROM prueba
) AS SourceTable
PIVOT(AVG([tna]) FOR [tipo] IN([entrada], [salida])) AS PivotTable
答案 1 :(得分:0)
即您可以汇总枢纽的结果。我不确定您对hora
有什么要求。
WITH Pivoted
AS
(
SELECT
*
FROM
(
SELECT [usuario],
[codtrab],
[tna],
[hora],
[tipo],
[fecha]
FROM prueba
group by [usuario],
) AS SourceTable PIVOT(AVG([tna]) FOR [tipo] IN([entrada], [salida])) AS PivotTable
)
SELECT
[usuario],
[codtrab],
min([hora]) as [hora],
[fecha],
max(entrada) as entrada,
max(salida) as salida
FROM Pivoted
GROUP BY [usuario], [codtrab], [fecha] ;