当列名是行时,连接表

时间:2018-06-04 16:00:10

标签: sql-server sql-server-2008 datetime join

我运行这样的查询:

SELECT      c.name  AS 'ColumnName'
        ,t.name AS 'TableName'
FROM        sys.columns c
JOIN        sys.tables  t   ON c.object_id = t.object_id
WHERE       (c.name='loaddate')
and (t.name like '%_agent%')
ORDER BY    TableName
        ,ColumnName;

返回:类似这样:

columnname|TableName
loaddate| gov_agent
loaddate| fin_agent
loaddate| sav_agent

在这些表中,存在loaddate列下的日期。例如,gov_agent可能如下所示:

  loaddate|entity|category
2018-06-01|James |A
2018-06-01|Jim   |B
2018-05-30|Bob   |B
2018-05-29|Kevin |C

我需要返回的是每个表中列出的日期的最大值,以便我的结果看起来像这样

loaddate| gov_agent|2018-06-01
loaddate| fin_agent|2018-06-01
loaddate| sav_agent|2018-03-02

我不知道有任何简单的方法来加入这些表格以便返回最大日期,或者甚至可以这样做。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:-1)

我无法对您的数据进行测试,但是,我确实在我的数据库中为表结构更改了它,这很有效。如果它不起作用,你有最好的朋友来帮助你。

USE YourDatabase;
GO
DECLARE @SQL nvarchar(MAX);

SET @SQL = N'SELECT' + STUFF((SELECT NCHAR(10) + N'UNION ALL' + NCHAR(10) +
                                      N'SELECT ' + QUOTENAME(c.[name],N'''') + N' AS ColumnName,' + NCHAR(10) +
                                      N'       ' + QUOTENAME(t.[name],N'''') + N' AS TableName,' + NCHAR(10) +
                                      N'       (SELECT MAX(' + QUOTENAME(c.[name]) + N') FROM ' + QUOTENAME(t.[name]) + N') AS MaxLoadDate'
                               FROM sys.columns c
                                    JOIN sys.tables t ON c.object_id = t.object_id
                               WHERE c.[name] ='loaddate'
                                 AND t.name LIKE '%[_]agent%' --I assumed that the understore is not meant to be a wildcard
                               FOR XML PATH(N'')),1,17,N'');
PRINT @SQL; --Your best friend
EXEC sp_executesql @SQL;