2009-08-14 10 views
4

Tableau - Employee.Status.XREFdossier avec la date max

Client Employee Date 
198  Jon Doe  3/1/2009 
198  Jon Doe  1/1/2009 

Tableau - Employee.Status.History

Client Employee Date  Status 
198  Jon Doe  5/21/2009 T 
198  Jon Doe  3/1/2009 A 
198  Jon Doe  1/1/2009 P 

enregistrements de requête uniquement dans les deux Employee.Status.History et Employee.Status.XREFClient, Employee et Date correspondance.

Retour uniquement l'enregistrement de Employee.Status.History la date max (par client par employee) Dans ce cas, il retournerait

Client Employee Date  Status 
198  Jon Doe  3/1/2009 A 

Répondre

0

MySql:

SELECT b.* FROM tableXREF a, tableSTATUS b 
WHERE b.client = a.client 
ORDER BY b.Date DESC 
LIMIT 1 

MSSQL:

SELECT TOP(1) b.field1, b.field2 etc. FROM tableXREF a, tableSTATUS b 
WHERE b.client = a.client 
ORDER BY b.Date DESC 

Je suppose ...

+0

Votre solution ne fonctionnera que s'il y a un utilisateur dans la base de données. L'astuce consiste à retourner les enregistrements avec l'historique maximum pour tous les utilisateurs. – Maciej

4

l'aide d'un sous-groupe de sélection & par:

select b.* 
from Employee.Status.History b, 
(select client, employee, max(date) date 
    from Employee.Status.XREF 
    group by client, employee 
) a 
where b.client = a.client 
and b.employee = a.employee 
and b.date = a.date 

La requête interne sélectionne la date la plus récente.
La requête externe renvoie l'intégralité de l'enregistrement à cette date pour le client et l'employé associés. Pourquoi ne pas utiliser une jointure avec une clause group by?

-1

select h.client,h.employee,max(h.date),h.Status 
from Employee.Status.History h inner join Employee.Status.XREF x on 
h.client=x.client and 
h.employee=x.employee and 
h.date=x.date 
group by h.client,h.employee,h.Status 
+0

max (h.date) retournera la même date pour chaque enregistrement renvoyé par le select (la date maximale de l'ensemble). OP attend la requête pour retourner l'enregistrement joint avec la date maximale. Ces deux choses sont très différentes et donc votre requête est incorrecte. – Maciej

1

Cela devrait fonctionner:

SELECT h.* 
FROM Employee.Status.History h 
INNER JOIN (
    SELECT h.Client, MAX(h.Date) AS MaxDate 
    FROM Employee.Status.History h 
    INNER JOIN Employee.Status.XREF x ON h.Client = x.Client 
     AND h.Employee = x.Employee AND h.Date = x.Date 
) q ON h.Client = q.Client