0

我在 Access 中有以下交叉表查询:

Transform Count(1) as Count
Select Cust,[Cust#],EntryDate,CloseDate
from Tbl1,Dates
where EntryDate>=[start date]
Group by Cust,[Cust#],EntryDate,CloseDate
Order by EntryDate
Pivot Quote;

我很难将其转换为 T-SQL。我应该使用 SSIS 进行 Pivot 转换来解决这个问题,还是我们有一个等效的 SQL Server 查询呢?

4

2 回答 2

1

我们真的没有足够的信息来转换特定的交叉表查询,所以这里有一个简单的示例可以帮助您实现目标:

对于名为 [Vehicles] 的表,其中包含...

VehicleID  VehicleMake  VehicleModel  VehicleType 
---------  -----------  ------------  ------------
        1  Ford         Focus         Compact car 
        2  Ford         F-150         Pickup truck
        3  Dodge        RAM 1500      Pickup truck
        4  Toyota       Tundra        Pickup truck
        5  Toyota       Prius         Hybrid car  
        6  Toyota       Tacoma        Pickup truck

...访问交叉表查询...

TRANSFORM Count(Vehicles.VehicleID) AS CountOfVehicleID
SELECT Vehicles.VehicleType
FROM Vehicles
GROUP BY Vehicles.VehicleType
PIVOT Vehicles.VehicleMake;

...返回:

VehicleType   Dodge  Ford  Toyota
------------  -----  ----  ------
Compact car             1        
Hybrid car                      1
Pickup truck      1     1       2

下面的 T-SQL 脚本完成了同样的事情

DECLARE 
        @ColumnList AS NVARCHAR(MAX),
        @SQL AS NVARCHAR(MAX)

-- build the list of column names based on the current contents of the table
--     e.g., '[Dodge],[Ford],[Toyota]'
--     required by PIVOT ... IN below
--     ref: http://stackoverflow.com/a/14797796/2144390     
SET @ColumnList = 
        STUFF(
            (
                SELECT DISTINCT ',' + QUOTENAME([VehicleMake])
                FROM [Vehicles] 
                FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'), 
            1, 
            1, 
            '')
SET @SQL = '
        WITH rollup
        AS
        (
            SELECT VehicleMake, VehicleType, COUNT(VehicleID) AS n FROM [Vehicles]
            GROUP BY VehicleMake, VehicleType
        )
        SELECT * FROM rollup
        PIVOT (SUM([n]) FOR [VehicleMake] IN (' + @ColumnList + ')) AS Results'
EXECUTE(@SQL)

它返回:

VehicleType   Dodge  Ford  Toyota
------------  -----  ----  ------
Compact car    NULL     1    NULL
Hybrid car     NULL  NULL       1
Pickup truck      1     1       2
于 2013-10-17T16:13:31.137 回答
0
drop table #tmpT1
select distinct UserField2 into #tmpT1 from CreateExcelForm
--select * from #tmpT1
DECLARE @PivotColumnHeaders VARCHAR(MAX)
SELECT @PivotColumnHeaders = 
COALESCE(
@PivotColumnHeaders + ',[' + cast(UserField2 as varchar) + ']',
'[' + cast(UserField2 as varchar)+ ']'
)
FROM #tmpT1
print(@PivotColumnHeaders)
DECLARE @PivotTableSQL NVARCHAR(MAX)
SET @PivotTableSQL = N'
SELECT *
FROM (
SELECT
* from CreateExcelForm
) AS PivotData
PIVOT (
max(StockCode)
FOR UserField2 IN (
' + @PivotColumnHeaders + '
)
) AS PivotTable
'

EXECUTE(@PivotTableSQL)
于 2014-10-20T20:53:12.443 回答