如何合并2个SQL查询

时间:2014-11-25 10:27:06

标签: sql-server asp-classic

我有2个查询我想要合并为1个结果(可能是2个)。

我有什么:

records

 id | action

我想要结果:

    最后添加行的
  1. optGroup 3行
  2. optGroup of 3 rows for most using action msg
  3. 所以,我试过了:

    enter image description here

    但是当我试图通过服务器端ASP页面显示时:

    sql = "SELECT TOP 3 [action],COUNT([id]) as pocet "  & vbcrlf &_
        "FROM [IT].[dbo].[records] "  & vbcrlf &_
        "GROUP BY [action] ORDER BY pocet desc; "  & vbcrlf &_
    "SELECT TOP 3 [action] "  & vbcrlf &_
        "FROM [IT].[dbo].[records] "  & vbcrlf &_
        "WHERE [email_numbers] <= 0  "  & vbcrlf &_
        "GROUP BY [inputdate] desc"
    

    使用Server.CreateObject("ADODB.Recordset")

    并尝试:

    response.write "<optgroup label='3 most used'>"
    while not rs.EOF
        response.write "<option value=''>" & rs("action") & "</option>"
        rs.movenext
    wend    
    response.write "</optgroup><optgroup label='3 last records'>"
    while not rs.EOF
        response.write "<option value=''>" & rs("action") & "</option>"
        rs.movenext
    wend
    response.write "</optgroup>"
    

    告诉我这个结果:

    SELECT TOP 3 [action],COUNT([id]) as c 
    FROM [IT].[dbo].[records] 
    GROUP BY [action] 
    ORDER BY c desc; 
    
    SELECT TOP 3 [action] 
    FROM [IT].[dbo].[records] 
    WHERE [email_numbers] <= 0 
    GROUP BY [inputdate] desc
    
    Microsoft OLE DB Provider for SQL Server error '80040e14'
    
    Incorrect syntax near the keyword 'desc'.
    
    /get.asp, line 1024 
    

    ADODB.RecordSet返回结果没有问题,SQL查询有问题或使用两次:while not rs.EOF

3 个答案:

答案 0 :(得分:0)

您可以在查询之间使用联合

select * from  1
union [all]
select * from 2

答案 1 :(得分:0)

问题在于SQL查询

SELECT TOP 3 [action] 
FROM [IT].[dbo].[records] 
WHERE [email_numbers] <= 0 
GROUP BY [inputdate] desc

您只能将desc关键字与ORDER BY一起使用,而不能与GROUP BY

一起使用

答案 2 :(得分:0)

您查询错误。您无法在DESC上使用GROUP BY键工作,删除它并且查询将有效:

SELECT TOP 3 [action],COUNT([id]) as c 
FROM [IT].[dbo].[records] 
GROUP BY [action] 
ORDER BY c desc; 

SELECT TOP 3 [action] 
FROM [IT].[dbo].[records] 
WHERE [email_numbers] <= 0 
GROUP BY [inputdate]

接下来,当你到达第一个记录集的EOF时,你需要继续下一个记录集:

Set rs = rs.NextRecordset

所以你的代码是:

response.write "<optgroup label='3 most used'>"
while not rs.EOF
    response.write "<option value=''>" & rs("action") & "</option>"
    rs.movenext
wend    
response.write "</optgroup><optgroup label='3 last records'>"

Set rs = rs.NextRecordset

while not rs.EOF
    response.write "<option value=''>" & rs("action") & "</option>"
    rs.movenext
wend
response.write "</optgroup>"