我有一个表,它是客户表和订单表的组合。它看起来像这样:
_______________________________________________________
| Id | Cust Id | Other Id | Date | Has Prod 1 | Has Prod 2 |
-------------------------------------------------------
| 1 | | 1 | 2009 | False | True |
| 2 | 1 | | 2008 | False | True |
| 3 | 2 | | 2008 | True | False |
| 4 | 1 | | 2009 | True | True |
| 5 | 2 | | 2009 | False | False |
| 6 | 1 | | 2010 | False | True |
-------------------------------------------------------
我知道我是否有客户的唯一方法是在Cust Id列中找到客户ID。 Cust Id和Other Id指向与此讨论无关的其他表。
我想做两件事:
我想制作一份报告或表格,总结客户并执行“Has”列的逻辑“或”,例如:
_________________________________________________
| Id | Cust Id | Other Id | Has Prod 1 | Has Prod 2 |
-------------------------------------------------
| 1 | 1 | | True | True |
| 2 | 2 | | True | False |
-------------------------------------------------
我想获取每个Cust Id组中的最新行,例如:
_______________________________________________________
| Id | Cust Id | Other Id | Date | Has Prod 1 | Has Prod 2 |
-------------------------------------------------------
| 5 | 2 | | 2009 | False | False |
| 6 | 1 | | 2010 | False | True |
-------------------------------------------------------
提前致谢。 GRB
答案 0 :(得分:1)
SELECT [Cust ID], MIN([Has Prod 1]) AS MinOne, MIN([Has Prod 2]) AS MinTwo
FROM customerorder
GROUP BY [Cust ID]
MIN()返回最小值。 -1为True,0为False,因此如果分组行的一条记录为True,则返回-1。
SELECT t1.*
FROM customerorder AS t1
INNER JOIN (SELECT [Cust ID], Max([Date]) As MaxDate
FROM customerorder
GROUP BY [Cust ID]) AS t2
ON ([t1].[Cust ID] = [t2].[Cust ID] AND [t1].[Date] = [t2].[MaxDate])
如果最后一行由Max([Date])确定,如示例数据所示,则上述查询将返回每个客户的最后一行。