【问题标题】:Subquery or conditional logic for result set结果集的子查询或条件逻辑
【发布时间】:2014-10-29 20:56:09
【问题描述】:

考虑模拟表

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;

对于如何为每个订单只返回一行以及产品的“是/否”逻辑的任何帮助将不胜感激。

谢谢

【问题讨论】:

  • 抱歉,这些表格没有保留原始文本框中的格式。试试这个
  • 请不要并排放置表格,这会使复制粘贴到 sqlfiddle 变得困难。

标签: mysql subquery conditional


【解决方案1】:

对于我在评论中回避的内容,如果您想使用它,我总是会使用 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

【讨论】:

  • @user3182105 你能接受一个答案吗?将不胜感激:)
【解决方案2】:

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

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

【讨论】:

  • 有趣...我总是以相反的方式“伪造”数据透视表 MAX(IF( 我想知道一种方法是否比另一种更好/更快?
  • 不确定哪个更好,可能差别不大。
  • 是的,听起来我应该在某个时候测试一下 :) +1 无论如何!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
  • 1970-01-01
  • 2011-07-16
  • 1970-01-01
  • 2016-02-05
相关资源
最近更新 更多