我有两个类似的查询。
如下:
with CategoryHistory AS (
SELECT
category.GUID as id,
----HERE MANY FIELDS----
category.__$operation AS operation,
map.tran_begin_time as beginT,
map.tran_end_time as endT
FROM cdc.fn_cdc_get_all_changes_dbo_EXT_BalanceHC_ZapasCategory(sys.fn_cdc_get_min_lsn('dbo_EXT_BalanceHC_ZapasCategory'), sys.fn_cdc_get_max_lsn(), 'all') AS category
INNER JOIN [cdc].[lsn_time_mapping] map
ON category.[__$start_lsn] = map.start_lsn
)
SELECT operation, fields, valueses, beginT, endT FROM CategoryHistory
unpivot ( [valueses] for fields in
(
----HERE MANY FIELDS----
))p
我可以UNION
WITH
结果吗?问题我想要UNPIVOT
来自查询结果的某些字段。
答案 0 :(得分:1)
也许你只是想要这样的东西:
SELECT ch.operation, ch.beginT, ch.endT, v.field, v.val
FROM CategoryHistory ch cross apply
(values ('field1', field1), ('field2', field2), . . .
) f(field, val);
我发现这比使用unpivot
更容易。