访问 - 如何在两个查询中拆分表记录

时间:2016-08-24 09:43:44

标签: sql ms-access access-vba

我有一张桌子"产品"有n条记录(超过5000并且总是更改数字)。如何基于表生成两个查询,一个用于上半部分记录,第二个用于另一半?

3 个答案:

答案 0 :(得分:1)

使用自动编号主键(或者至少是一个没有数字缺失的连续编号的字段),这可能有效 - 尽管我还没有真正考虑过它,可能会有一些陷阱?

返回身份证号码的前半部分:

SELECT  ID
FROM    Table1
WHERE   ID<=INT((SELECT MAX(ID) FROM Table1)/2)

返回身份证号码的后半部分:

SELECT  ID
FROM    Table1
WHERE   ID>INT((SELECT MAX(ID) FROM Table1)/2)

答案 1 :(得分:0)

问题是您无法在TOP指令中指定COUNT(*)子查询的结果,因此无法在纯SQL中100%可靠地执行此操作

可靠的替代方案是使用VBA预先构建2个查询:

Sub Half_Table()

    Dim lngTotal As Long
    Dim lngHalf1 As Long
    Dim lngHalf2 As Long

    Dim strTable As String
    Dim strIDfield As String
    Dim strSQL1 As String
    Dim strSQL2 As String


    strTable = "table_Name"
    strIDfield = "ID"

    lngTotal = DCount("*", strTable)
    lngHalf1 = Round(lngTotal / 2)
    lngHalf2 = lngTotal - lngHalf1

    strSQL1 = "SELECT TOP " & lngHalf1 & " * FROM " & strTable & " ORDER BY " & strIDfield & " ASC"
    strSQL2 = "SELECT TOP " & lngHalf2 & " * FROM " & strTable & " ORDER BY " & strIDfield & " DESC"

    Debug.Print strSQL1
    Debug.Print strSQL2


End Sub

相应地更改strTablestrIDfield个名称。

这将生成以下2个查询,其中包含1399条记录的表:

SELECT TOP 700 * FROM table_Name ORDER BY ID ASC
SELECT TOP 699 * FROM table_Name ORDER BY ID DESC

我没有展示如何使用生成的SQL查询  事后我假设你知道

答案 2 :(得分:0)

使用行号计数聚合子查询来考虑纯SQL解决方案:

TOP HALF

SELECT [ID], [Category], [Product], [Price]
FROM Products
INNER JOIN 
   (SELECT [ID], 
           (SELECT Count(*) FROM Products t2 
            WHERE Products.[ID] <= t2.[ID]) AS ProductOrder, 
           (SELECT Count(*) FROM Products t2) AS ProductCount
    FROM Products) AS sub 
ON Products.[ID] = sub.[ID]
WHERE sub.ProductOrder >= sub.ProductCount / 2

BOTTOM HALF

SELECT [ID], [Category], [Product], [Price]
FROM Products
INNER JOIN 
   (SELECT [ID], 
           (SELECT Count(*) FROM Products t2 
            WHERE Products.[ID] <= t2.[ID]) AS ProductOrder, 
           (SELECT Count(*) FROM Products t2) AS ProductCount
    FROM Products) AS sub 
ON Products.[ID] = sub.[ID]
WHERE sub.ProductOrder <= sub.ProductCount / 2