开发者

Information from un-normalized table

开发者 https://www.devze.com 2023-03-25 09:10 出处:网络
I have a table that is a combination of a customer table and an orders table. It looks something like this:

I have a table that is a combination of a customer table and an orders table. It looks something like this:

_______________________________________________________
| 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       |
-------------------------------------------------------

The only way I know if I have a customer is to find a customer Id in the Cust Id column. The Cust Id and Other Id point to other tables which are irrelevant to this discussion.

I would like to do 2 things:

I would like to produce a report or table that summarizes the customers and performs a logical “or” of the “Has” columns, such as this:

_________________________________________________
| Id | Cust Id  | Other Id | Has Prod 1 | Has Prod 2 |
-------------------------------------------------
| 1  | 1        |          | True       | True       |
| 2  | 2        |          | True       | False      |
-------------------------------------------------

I would like to obtain the latest row within each Cust Id group, such as this:

_______________________________________________________
| Id | Cust Id  | Other Id | Date | Has Prod 1 | Has Prod 2 |
-------------------------------------------------------
| 5  | 2        |          | 2009 | False      | False      |
| 6  | 1        |          | 2010 | False      | True       |
-------------------------------------------------------

Thanks in advance. GRB


SELECT [Cust ID], MIN([Has Prod 1]) AS MinOne, MIN([Has Prod 2]) AS MinTwo
FROM customerorder
GROUP BY [Cust ID]

MIN() returns the smallest value. -1 is True and 0 is False, so if one record of the grouped rows is True, -1 is returned.

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])

If the last row is determined by Max([Date]), as is indicated by your sample data, the above query will return the last row for every customer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号