有没有办法从表1中获得TOP N记录,其中N基于表2

时间:2016-01-22 14:00:06

标签: sql

表1

Rowno   name         Date
------------------------------------
1     sathish        Dec 21    
2     kumar          Dec 22
3     sathish        Dec 21
4     sathish        Dec 22
5     sathish        Dec 21
5     sathish        Dec 22

表2

Date          NoofTran
-----------------------
Dec22            2
Dec21            1

我希望根据table1 table2值随机获取nooftran的记录。

在12月22日,表2中的交易数量为2,因此两个记录应该在相应的日期从表1中获取,它应该是随机的。因此,在12月22日的3条记录中,有两条应随机出现。

我应该使用哪种SQL查询?

2 个答案:

答案 0 :(得分:1)

{{1}}

答案 1 :(得分:1)

如果您使用的是SQL Server,则可以使用此类交叉应用

Function loadData()

    Dim strPathFile As String, strFile As String, strPath As String
    Dim strTable As String
    Dim blnHasFieldNames As Boolean

    ' Change this next line to True if the first row in EXCEL worksheet
    ' has field names
    blnHasFieldNames = True

    ' Replace C:\Documents\ with the real path to the folder that
    ' contains the EXCEL files
    strPath = "C:\Bdz outputs\"

    ' Replace tablename with the real name of the table into which
    ' the data are to be imported

    strFile = Dir(strPath & "*.xlsx")
    strTable = Left(strFile, 8)
    strPathFile = strPath & strFile
    'Debug.Print (createTable("hello", "asdasd"))

    Do While Len(strFile) > 0
        strPathFile = strPath & strFile
        DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "Table1", strPathFile, False

        ' Uncomment out the next code step if you want to delete the
        ' EXCEL file after it's been imported

        'Kill strPathFile

        strFile = Dir()

    Loop

End Function

示例

select t1.*
from Table2 as t2
cross apply
(
   select top (select T2.nooftran) *
   from Table1 as t1
   where t2.Date = t1.date
   order by newid()       
) as t1