结果集的子查询或条件逻辑

时间:2014-09-05 00:09:56

标签: mysql subquery conditional

考虑模拟表

ORDERS                          
OrderID CustID date              
10       1     2014-01-01       
11       3     2014-02-01       
12       2     2014-03-01        

CUSTOMER 
CustID FName LName
1      Jon   Doe         
2      Jane  Doe
3      Mike  Brown

LINEITEM                        
OrderID ProdID                  
10      1                        
10      3                       
11      2                       
12      1
12      2

PRODUCTS
ProdID Description 
1      Apple
2      Orange
3      Grape

我想返回一个如下所示的结果集:

OrderID CustomerLastName Apple Orange Grape
11      Brown            No    Yes    No
12      Doe              Yes   Yes    No

逻辑:选择orderID,客户姓氏,确定他们是否购买了每种产品(是或否)        对于订单日期大于2014-01-01的所有订单。

这是我能得到的

select O.OrderID as 'OrderID', 
       C.LName as 'CustomerLastName', 
      (some conditional or subquery for figuring out yes or no) as 'Apple',
      (some conditional or subquery for figuring out yes or no) as 'Orange',
      (some conditional or subquery for figuring out yes or no) as 'Grape'
from ORDERS O join CUSTOMER C using (CustID)
              join LINEITEM using (OrderID)
              join Products P using (ProdID)
where O.date > 2014-01-01;

任何有关如何为每个订单返回一行的帮助以及产品的YES / NO逻辑将不胜感激。

由于

2 个答案:

答案 0 :(得分:1)

这基本上只是表格的一个支点。与通常的枢轴的唯一区别是,您只需要一个是/否,而不是每个旋转列的行的聚合值。

SELECT O.OrderID, C.LName AS CustomerLastName,
        IF(MAX(P.Description = 'Apple'), 'Yes', 'No') AS Apple,
        IF(MAX(P.Description = 'Orange'), 'Yes', 'No') AS Orange,
        IF(MAX(P.Description = 'Grape'), 'Yes', 'No') AS Grape
FROM ORDERS AS O
JOIN CUSTOMER AS C USING (CustID)
JOIN LINEITEM AS L USING (OrderID)
JOIN Products AS P USING (ProdID)
WHERE O.date > '2014-01-01'
GROUP BY O.OrderID, C.CustID

DEMO

答案 1 :(得分:0)

对于我在评论中遗漏的内容,如果你想玩它,我总是会伪造一个使用MAX的数据透视表(然后是一个条件语句):)

SELECT 
    O.OrderID, C.LName AS CustomerLastName,
    MAX(CASE WHEN P.Description = 'Apple' THEN 'Yes' ELSE 'No' END) AS Apple,
    MAX(CASE WHEN P.Description = 'Orange')THEN 'Yes' ELSE 'No' END) AS Orange,
    MAX(CASE WHEN P.Description = 'Grape')THEN 'Yes' ELSE 'No' END) AS Grape
FROM ORDERS AS O
JOIN CUSTOMER AS C USING (CustID)
JOIN LINEITEM AS L USING (OrderID)
JOIN Products AS P USING (ProdID)
WHERE O.date > '2014-01-01'
GROUP BY O.OrderID, C.CustID