SQL查询联合

时间:2017-03-18 02:04:50

标签: sql

我有这个查询

SELECT e.ename, SUM(md.prices) AS TotalSales
FROM Employee2 e inner join MakesD2 md on md.eid=e.eid
GROUP BY e.ename
UNION ALL
SELECT e.ename
FROM Employee2 e left join MakesD2 md on md.eid=e.eid
WHERE md.eid is NULL;

但我一直收到这个错误。我能以任何方式解决它吗?

3 个答案:

答案 0 :(得分:1)

union all必须为所有子查询使用相同的列。所以,添加第二列:

SELECT e.ename, SUM(md.prices) AS TotalSales
FROM Employee2 e inner join MakesD2 md on md.eid=e.eid
GROUP BY e.ename
UNION ALL
SELECT e.ename, NULL
FROM Employee2 e left join MakesD2 md on md.eid=e.eid
WHERE md.eid is NULL;

您的查询可能不需要union all。这可能是你想要的:

SELECT e.ename, SUM(md.prices) AS TotalSales
FROM Employee2 e left join
     MakesD2 md
    on md.eid = e.eid
GROUP BY e.ename;

但是,这更接近原始版本(因为name可能会在您的查询中多次出现):

SELECT e.ename, SUM(md.prices) AS TotalSales
FROM Employee2 e left join
     MakesD2 md
    on md.eid = e.eid
GROUP BY e.ename, (CASE WHEN md.eid IS NULL THEN 1 ELSE 2 END);

此版本仅包含name一次,即使Employee2中有多个行与给定名称MakesD2不匹配。

答案 1 :(得分:0)

  • 列数出现在相应的SELECT语句中 必须是平等的。
  • 列出现在每个SELECT的相应位置 语句必须具有相同的数据类型,或者至少是可转换的数据 类型。

你可以这样做

$ ls -1 /cygdrive/c/Program\ Files\ \(x86\)/SQLite\ ODBC\ Driver/
adddsn.exe
addsysdsn.exe
inst.exe
instq.exe
license.terms
license.txt
README
readme.txt
remdsn.exe
remsysdsn.exe
sqlite3.exe
sqlite3_mod_blobtoxy.dll
sqlite3_mod_csvtable.dll
sqlite3_mod_extfunc.dll
sqlite3_mod_fts3.dll
sqlite3_mod_impexp.dll
sqlite3_mod_rtree.dll
sqlite3_mod_zipfile.dll
sqlite3odbc.dll
sqlite3odbcnw.dll
uninst.exe
Uninstall.exe
uninstq.exe

答案 2 :(得分:0)

请尝试以下查询:

    SELECT e.eid, e.ename, COALESCE(SUM(md.prices), 0) AS TotalSales
    FROM Employee2 e 
    LEFT JOIN MakesD2 md
    ON md.eid = e.eid
    GROUP BY e.eid, e.ename
    ORDER BY e.ename, e.eid