我需要在一张桌子上使用两个过滤器。
我尝试UNION ALL
但它不起作用。
有没有办法重新编写TSQL以合并两个过滤器以获取合并的结果数据集?
谢谢!
DECLARE @TimeStart datetime
DECLARE @TimeEnd datetime
SET @TimeStart = '20180123'
SET @TimeEnd = '20180124'
;WITH A ([Machine], [TimeStart], [TimeEnd])
AS
(
SELECT machine, [СИЗА: Calib Start] as [TimeStart],[СИЗА: Calib Stop] as [TimeEnd]
FROM
(
SELECT Machine, [AtTime], [ValueString]
FROM [STC_DB].[dbo].[DATA_ACTION]
WHERE AtTime BETWEEN @TimeStart AND @TimeEnd
AND ([ValueInt] IN (16,17))
AND (ValueString LIKE '%СИЗА: Calib Start%' OR ValueString LIKE '%СИЗА: Calib Stop%' )
) d
PIVOT
(
MAX(AtTime)
FOR [ValueString] in ([СИЗА: Calib Start] , [СИЗА: Calib Stop])
) piv
)
SELECT [Machine], (SELECT FullName FROM MachineModelShortView MM WHERE MM.MachineID = A.[Machine]) AS FullName, [TimeStart], [TimeEnd] FROM A
UNION ALL--- It does not work with ;WITH coz of ;
;WITH A ([Machine], [TimeStart], [TimeEnd])
AS
(
SELECT machine, [СИЗ: Calib Start] as [TimeStart],[СИЗ: Calib Stop] as [TimeEnd]
FROM
(
SELECT Machine, [AtTime], [ValueString] FROM [STC_DB].[dbo].[DATA_ACTION]
WHERE AtTime BETWEEN @TimeStart AND @TimeEnd AND ([ValueInt] IN (15, 16)) AND (ValueString LIKE '%СИЗ: Calib Start%' OR ValueString LIKE '%СИЗ: Calib Stop%' ) AND [Action] = 80
) d
PIVOT
(
MAX(AtTime)
FOR [ValueString] in ([СИЗ: Calib Start] , [СИЗ: Calib Stop])
) piv
)
SELECT [Machine], (SELECT FullName FROM MachineModelShortView MM WHERE MM.MachineID = A.[Machine]) AS FullName, [TimeStart], [TimeEnd] FROM A
答案 0 :(得分:2)
如何将这两个条件与OR
合并,并将ValueString
更改为Calib Start
和Calib End
?它还会给你相同的结果吗?
;WITH A ([Machine], [TimeStart], [TimeEnd])
AS
(
SELECT machine, [Calib Start] as [TimeStart],[Calib Stop] as [TimeEnd]
FROM
(
SELECT Machine,
[AtTime],
CASE WHEN ValueString LIKE '%Calib Start%' THEN 'Calib Start' ELSE 'Calib Stop' END [ValueString]
FROM [STC_DB].[dbo].[DATA_ACTION]
WHERE (
AtTime BETWEEN @TimeStart AND @TimeEnd
AND ([ValueInt] IN (16,17))
AND (ValueString LIKE '%Calib Start%' OR ValueString LIKE '%Calib Stop%' )
)
OR
(
AtTime BETWEEN @TimeStart AND @TimeEnd
AND ([ValueInt] IN (15, 16))
AND (ValueString LIKE '%СИЗ: Calib Start%' OR ValueString LIKE '%СИЗ: Calib Stop%' )
AND [Action] = 80
)
) d
PIVOT
(
MAX(AtTime)
FOR [ValueString] in ([Calib Start] , [Calib Stop])
) piv
)
SELECT [Machine],
(SELECT FullName FROM MachineModelShortView MM WHERE MM.MachineID = A.[Machine]) AS FullName,
[TimeStart],
[TimeEnd]
FROM A