1

我有一个带有以下表格的数据库:

具有以下列的 customer_info 表:

custID | storeName     | accName
  1    |  bayport      | name one
  2    |  plainfield   | name two
  3    |  bayport      | name three

处理具有以下列的表:

dealID | dealDate     | custID
  1    | 2012-10-15   |   1
  2    | 2012-11-25   |   2
  3    | 2012-12-17   |   3
  4    | 2012-12-17   |   1

具有以下列的 phone_details 表

phone_ID  | instore  | online  | received | dealID  
    1     |    1     |    0    |    0     |   1
    2     |    1     |    0    |    0     |   1
    3     |    0     |    1    |    1     |   1    
    4     |    0     |    1    |    0     |   2
    5     |    0     |    1    |    0     |   3
    6     |    0     |    1    |    1     |   3
    7     |    1     |    0    |    1     |   4
    8     |    1     |    0    |    1     |   4

发票明细

payment_ID   | due  | paid | tender | dealID
      1      | 1000 | 500  | cash   |    1    
      2      | 500  | 100  | credit |    2 
      3      | 200  | 200  | cash   |    3 
      4      | 350  | 350  | debit  |    4

如何查询此表,以便我的结果在某个日期看起来像这样?

例如,2012-10-15 - 2012-11-25 它看起来像这样

               | bayport |   plainfield 
# of instore   |    2    |       0
# of online    |    1    |       1
total          |    3    |       1
# of received  |    1    |       0
total amount   |  1000   |      500
4

2 回答 2

3

与@MichaelBerkowski的出色答案相比,如果您可以容忍以bayport/plainfield 作为行和instore/online 作为列的数据(根据上面的评论),您可以简单地执行以下操作:

SELECT    c.storeName,
          SUM(p.instore) AS `# of instore`,
          SUM(p.online ) AS `# of online`
FROM      customer_info c
LEFT JOIN deals         d
       ON d.custID    = c.custID
      AND d.dealDate  = '2012-10-15'
LEFT JOIN phone_details p USING (dealID)
GROUP BY  storeName

sqlfiddle上查看。

于 2013-01-04T02:03:10.050 回答
2

这绝对是一个奇怪的配置。

这将需要 a UNION ALLwhich 获取每个的onlineinstore值,以使它们成为行而不是列。然后使用 a 将其旋转SUM(CASE...)以将商店名称转换为列。

SELECT 
  calltype,
  /* In the outer query, pivot the storeName */
  SUM(CASE WHEN storeName = 'bayport' THEN num ELSE 0 END) AS bayport,
  SUM(CASE WHEN storeName = 'plainfield' THEN num ELSE 0 END) AS plainfield
FROM (
    /* First half gets the instore */
    SELECT
      /* String literal for label column */
      '# of instore' AS calltype,
      COUNT(*) AS num,
      storeName
    FROM
      customer_info c
      LEFT JOIN deals d ON c.custID = d.custID
      LEFT JOIN phone_details p ON d.dealID = p.dealID
    WHERE instore = 1 AND dealDate = '2012-10-15'
    GROUP BY storeName, calltype
    UNION ALL
    /* Second half gets the online */
    SELECT
      '# of online' AS calltype,
      SUM(online) AS num,
      storeName
    FROM
      customer_info c
      LEFT JOIN deals d ON c.custID = d.custID
      LEFT JOIN phone_details p ON d.dealID = p.dealID
    WHERE online = 1 AND dealDate = '2012-10-15'
    GROUP BY storeName, calltype
) totals 
GROUP BY calltype, storeName

http://sqlfiddle.com/#!2/af18b/13

于 2013-01-04T01:46:11.630 回答