sqlite 如何正确组合这两个查询呢?

mspsb9vt  于 2022-11-14  发布在  SQLite
关注(0)|答案(1)|浏览(190)

Employees表:
EmpID(主键)|姓氏|名字
-|-|
Orders表:
OrderID(主键)|CustID|EmpID|OrderDate|RequiredDate|发货日期
-|
我需要一个查询,它返回EmpIDLastNameFirstName、员工订单总数和延迟发货的订单总数。如果订单的ShippedDateRequiredDate之后5天,则订单延迟。我是通过以下方式收到延迟发货的:

julianday(ShippedDate) - julianday(RequiredDate) >= 5

我想进行两个独立的查询,一个获取提交的总数,另一个获取延迟订单的总数,然后UNION。我没有得到我想要的结果:

SELECT Employees.EmpId, Employees.LastName, Employees.FirstName, COUNT(*) as TotalCount, NULL
FROM Orders, Employees
WHERE Orders.EmpID = Employees.EmpID
GROUP BY LastName
UNION
SELECT Employees.EmpId, Employees.LastName, Employees.FirstName, NULL, COUNT(*) as LateCount
FROM Orders, Employees
WHERE Orders.EmpID = Employees.EmpID
AND julianday(ShippedDate) - julianday(RequiredDate) >= 5
GROUP BY LastName

我在表的右侧得到了偏移量空值:
TotalCount|空

17|空
空|25
等。
1.我的工会出了什么问题?为什么数据偏移量和列标题错误?
1.有没有更好的办法?

wztqucjr

wztqucjr1#

有没有更好的办法?
JOIN而不是UNION

SELECT
    Employees.EmpID,
    Employees.LastName,
    Employees.FirstName,
    count(*) AS TotalCount,
    sum(
        julianday(Orders.ShippedDate) - julianday(Orders.RequiredDate) >= 5
    )        AS LateCount
FROM
    Employees
JOIN Orders ON Orders.EmpID = Employees.EmpID
GROUP BY
    Employees.EmpID
ORDER BY
    TotalCount DESC,
    LateCount  DESC

相关问题