从结果查询输出中查找最大值(日期)

时间:2014-12-31 05:52:24

标签: sql sql-server-2008 join sqldatetime

我有两张桌子:

表1

objName | rptName | srcTblName | srcFileName | srcDateColName
--------------------------------------------------------------
obj1    | rpt1    | srcTbl1    | srcFile1.csv| srcDate

表2

FileName     | FileSize
------------------------
srcFile1.csv | 2009

以下查询为我提供了不同的表和日期列名称。

SELECT DISTINCT a.srcTblName, a.SrcDateColName
FROM table1 a
LEFT JOIN table2 b
ON a.srcFileName LIKE b.FileName
WHERE a.srcTblName is NOT NULL
AND a.srcFileName is NOT NULL

输出

srcTblName               |  srcDateColName
---------------------------------------------
tableN                   |    EntryDate
tableO                   |    Modified_Date

输出的第二列是 SrcTblName 中的 COLUMN_NAME ,这是一个日期

我想从同一查询中的相应 srcTblName 中找到 max(srcDateColName)。 任何人都可以帮我修改上述查询吗?

4 个答案:

答案 0 :(得分:1)

由于必须从表中执行tablename和datecolumn,因此必须使用动态sql

SELECT * INTO tableN FROM
(
SELECT '01/JAN/2014' EntryDate
UNION ALL
SELECT '24/JAN/2014'
UNION ALL
SELECT '13/MAR/2014'
)TAB


SELECT * INTO tableO FROM
(
SELECT '11/APR/2014' Modified_Date
UNION ALL
SELECT '18/MAY/2014'
UNION ALL
SELECT '22/JUN/2014'
)TAB

SELECT * INTO NEWTBL FROM
(
  SELECT 'tableN' srcTblName,'EntryDate' srcDateColName
  UNION ALL
  SELECT 'tableO' ,'Modified_Date' 
)TAB

创建临时表以获得结果

CREATE TABLE #TEMP(srcTblName VARCHAR(100),srcDateColName VARCHAR(100),NEWDATE DATE)

现在使用游标并动态执行

DECLARE @TABLENAME VARCHAR(100)
DECLARE @COLUMNNAME VARCHAR(100)

-- Here you declare which all columns you need to loop in Cursor
DECLARE CUR CURSOR FOR 

-- Use your SELECT here instead of SELECT srcTblName , srcDateColName FROM NEWTBL

--SELECT DISTINCT a.srcTblName, a.SrcDateColName
--FROM table1 a
--LEFT JOIN table2 b
--ON a.srcFileName LIKE b.FileName
--WHERE a.srcTblName is NOT NULL
--AND a.srcFileName is NOT NULL

SELECT srcTblName , srcDateColName
FROM NEWTBL


OPEN CUR

-- Select each tablename and datecolumn and execute dynamically 
FETCH NEXT FROM CUR 
INTO @TABLENAME,@COLUMNNAME

WHILE @@FETCH_STATUS = 0
BEGIN

    DECLARE @QRY NVARCHAR(MAX) 

    SET @QRY = '
            INSERT INTO #TEMP
            SELECT '''+@TABLENAME+''' , '''+@COLUMNNAME+''',
            (SELECT MAX(CAST('+@COLUMNNAME+' AS DATE))ENDT FROM '+@TABLENAME+')AA                              
            '

    EXEC SP_EXECUTESQL @QRY

    -- Fetches next record and increments the loop
    FETCH NEXT FROM CUR 
    INTO @TABLENAME,@COLUMNNAME
END 

CLOSE CUR;
DEALLOCATE CUR;

答案 1 :(得分:0)

使用以下查询,希望它能为您提供帮助。

SELECT  a.srcTblName, max(a.SrcDateColName)
FROM table1 a
LEFT JOIN table2 b
ON a.srcFileName LIKE b.FileName
WHERE a.srcTblName is NOT NULL
AND a.srcFileName is NOT NULL
group by a.srcTblName

答案 2 :(得分:0)

这里你可以做什么

declare @name varchar(50),
        @column varchar(50),
        @query varchar(max)

declare @table table(TableName varchar(50),
                     MaxDate datetime)

declare c cursor for
-- your query here
SELECT DISTINCT a.srcTblName, a.SrcDateColName
FROM t1 a
LEFT JOIN t2 b
ON a.srcFileName LIKE b.FileName
WHERE a.srcTblName is NOT NULL
AND a.srcFileName is NOT NULL

open c
fetch next from c into @name,@column
while @@fetch_status=0
begin
  -- executing the code for each table mentioned in your srcTblName
  set @query='select ''' + @name + ''' as TableName,max(' + @column + ') as Date from ' + @name
  --print @query
  insert into @table(TableName,MaxDate)
  exec(@query)
  fetch next from c into @name,@column
end
close c
deallocate c

select * from @table

这是一个有效的DEMO

希望它会帮助你

答案 3 :(得分:0)

Hadi和Sarath给出的答案似乎有效,但光标似乎影响了性能。所以我使用TEMP表如下所示:

DECLARE @OBJECT_NAME VARCHAR(50) = 'ObjName'      

BEGIN
DECLARE @Query NVARCHAR(1000),@COUNT INT, @MAX_Count INT, @rptName VARCHAR(255)
DECLARE @tblName varchar(100),@dateColName varchar(100), @max_Date Date,@fileName varchar(100),@refID INT

DECLARE @Temp_Table TABLE([RowNumber] INT,rptName VARCHAR(500),SrcTblName VARCHAR(500), DateColName VARCHAR(100), SrcFileName VARCHAR(600), RefID INT)
INSERT INTO @Temp_Table
SELECT
    ROW_NUMBER()OVER(ORDER BY rptName)
    ,rptName
    ,srcTblName
    ,srcDateColName
    ,srcFileName
    ,ID
FROM
    table1
WHERE
    objName  = @OBJECT_NAME

SELECT @MAX_Count = MAX(RowNumber) FROM @Temp_Table
SET @COUNT = 1
WHILE (@COUNT <= @MAX_Count)
BEGIN                   
    SELECT   
        @rptName = rptName,
        @tblName = SrcTblName,
        @fileName = SrcFileName,
        @dateColName = DateColName,
        @refID = RefID    
    FROM   
        @Temp_Table   
    WHERE   
        RowNumber = @COUNT 

    IF @tblName IS NOT NULL AND @fileName IS NOT NULL AND @dateColName IS NOT NULL
    BEGIN
        SET @Query = 'SELECT @max_Date = MAX(CONVERT(DATE, ' + @dateColName + ')) FROM ' + @tblName
            EXEC SP_EXECUTESQL @Query, N'@max_Date DATE OUTPUT', @max_DATE OUTPUT

    END
SET @COUNT = @COUNT + 1
END

END

我希望这能帮助那些寻找类似解决方案的人。 谢谢你的帮助,但是:)