我正在尝试将所有一系列发票和非发票数据合并在一起。每批数据(开票/非开票)从各种临时表中检索数据,我想通过将1分配给已开发票而将0分配给非开票来带来所有数据,这样当我在Excel中导出数据时,我可以基于过滤掉在那个标准上。
现在,我有点不确定如何使用UNION ALL将所有数据组合在一起。我发布了一个查询片段。我的理解是在我当前查询的末尾使用UNION并带来第二个选择(对于未开票的数据)。我遇到的另一个问题是,写作...(创建表格......)似乎并不正确。有任何想法吗?
WITH CTE_Invoiced (DateCreatedInvoiced, [Destination Country], [Destination Depot]) AS
(SELECT DateCreatedInvoiced,
DestinationCountry,
DestinationDepot
FROM (CREATE TABLE #tempResults
(
[DateCreatedInvoiced] DATETIME NOT NULL,
[Destination Country] VARCHAR (15) NOT NULL,
[Destination Depot] VARCHAR (15) NOT NULL
INSERT INTO #tempResults
SELECT
-- DISTINCT
MAX(CAST(ME.InvoicedDate AS DATE)) AS [Invoice Date1],
MIN(CR.DestinationCountry) AS [Destination Country],
MIN(t1.DestinationDepot) AS [Destination Depot],
FROM dbo.movMovement AS MM
INNER JOIN dbo.MALExport AS ME
ON MM.MovementRef = ME.MovementReference
INNER JOIN dbo.movConLink AS MCL
ON ME.ConsignmentReference = MCL.ConsignmentReference
AND MCL.MovementID = MM.MovementID
INNER JOIN dbo.cgtRoute AS CR
ON CR.RouteID = MCL.CMRRouteID
LEFT JOIN #tempCompare1 t1
ON t1.MovementID = MM.MovementID --this is a temporary table used in calculations
LEFT JOIN dbo.movUnit AS MU
ON MU.UnitID = MM.TrailerID
WHERE cr.DestinationCountry <> 'SF'
AND CR.DestinationDepot <> 'BSB'
AND ( MM.SailingDateTime BETWEEN @startDate AND @endDate )
GROUP BY MM.MovementRef,
MM.MovementID
ORDER BY mm.MovementRef;
CREATE INDEX IDX_tempresults
ON #tempResults ([Movement Reference])
答案 0 :(得分:2)
您最初创建临时表并用数据填充它。
然后你可以SELECT
从它。
所以,你需要做的是:
CREATE TABLE #tempResults (
[DateCreatedInvoiced] DATETIME NOT NULL,
[Destination Country] VARCHAR (15) NOT NULL,
[Destination Depot] VARCHAR (15) NOT NULL
)
然后插入此表:
INSERT INTO #tempResults
SELECT Max(Cast(ME.InvoicedDate as Date)) AS [Invoice Date1] ,
MIN(CR.DestinationCountry) AS [Destination Country] ,
MIN(t1.DestinationDepot) AS [Destination Depot]
FROM dbo.movMovement AS MM
INNER JOIN dbo.MALExport AS ME ON MM.MovementRef = ME.MovementReference
INNER JOIN dbo.movConLink AS MCL ON ME.ConsignmentReference = MCL.ConsignmentReference AND MCL.MovementID = MM.MovementID
INNER JOIN dbo.cgtRoute AS CR ON CR.RouteID = MCL.CMRRouteID
LEFT JOIN #tempCompare1 t1 ON t1.MovementID = MM.MovementID --this is a temporary table used in calculations
LEFT JOIN dbo.movUnit AS MU ON MU.UnitID = MM.TrailerID
WHERE cr.DestinationCountry <> 'SF'
AND CR.DestinationDepot <> 'BSB'
AND ( MM.SailingDateTime BETWEEN @startDate AND @endDate )
GROUP BY MM.MovementRef, MM.MovementID
ORDER BY mm.MovementRef
您还可以从此表中选择以下内容来检查您的需求:
SELECT [DateCreatedInvoiced],
[Destination Country],
[Destination Depot]
FROM #tempResults
在这种情况下,您可以在不使用CTE
的情况下执行此操作。