我通过以下方式拥有3张桌子:
每个客户可以拥有一张以上的卡,一张卡可以进行的交易不止于此。
我要执行以下操作:以少量交易获得3个客户。
我的问题:我的查询返回了2次客户端。
SELECT TOP 3
ClientId, Name, LastName, QtyTrans
FROM
(SELECT
ClientId, Name, LastName, 0 AS QtyTrans
FROM
Client
JOIN
Card ON ClientId = IdClient
WHERE
CardId NOT IN (SELECT CardId FROM Transaction)
GROUP BY
ClientId, Name, LastName
UNION
SELECT
ClientId, Name, LastName, COUNT(TransId) AS QtyTrans
FROM
Client
JOIN
Card c ON ClientId = IdClient
JOIN
Transaction t ON c.CardId = t.CardId
GROUP BY
ClientId, Name, LastName
) TotalTrans
ORDER BY
QtyTrans
当客户使用每张卡进行交易时,只返回一行,但是如果其中一张卡没有交易,则返回一行的计数为0,另一行则为其他卡交易的总和。
结果:
11 Martin Camejo 0,
7 Matias Barrenechea 0,
7 Matias Barrenechea 2
有帮助吗?
答案 0 :(得分:0)
我要执行以下操作:以少量交易获得3个客户。
我不知道UNION
与这个问题有什么关系。您只需要LEFT JOIN
和GROUP BY
:
SELECT TOP (3) cl.ClientId, cl.Name, cl.LastName,
COUNT(t.CardId) AS QtyTrans
FROM Client cl LEFT JOIN
Card c
ON cl.ClientId = c.IdClient LEFT JOIN -- don't know which table has which column
Transaction t
ON t.CardId = c.CardId
GROUP BY cl.ClientId, cl.Name, cl.LastName
ORDER BY QtyTrans ASC;