0

这是我所拥有的粗略想法:

+---------------+   +-----------------+    +---------------+
| customers     |   | transactions    |    | branches      |
+---------------+   +-----------------+    +---------------+
| customerid    |   | orderid         |    | branchid      |
|               |   | customerid (FK) |    |               | 
|               |   | branchid (FK)   |    |               | 
+---------------+   | datetime        |    +---------------+
                    +-----------------+

我将如何创建一个查询来获取每天/每周/等的交易计数。但是对于每个 branchid分别

我试过这样的工会(只计算所有星期六)。这给出了一个结果,但不是所需的格式。

SELECT COUNT(orderid) as count1 FROM transactions WHERE WEEKDAY(datetime) = 5 
AND branchid = 'branch1' 
UNION 
SELECT COUNT(orderid) as count2 FROM transactions WHERE WEEKDAY(datetime) = 5 
AND branchid = 'branch2'

返回:

+------------+
|   count1   |
+------------+
|        152 |
|         48 |
+------------+

而我希望数据格式如下:

+------------+------------+
|   count1   |   count2   |
+------------+------------+
|        152 |         48 |
|            |            |
+------------+------------+

有人对如何做到这一点有任何提示吗?提前致谢!

4

3 回答 3

2

奇怪的是,您希望它作为列而不是行,但我相信这应该满足您的要求:

SELECT
(SELECT COUNT(orderid) as count1 FROM transactions WHERE WEEKDAY(datetime) = 5 
AND branchid = 'branch1'),
(SELECT COUNT(orderid) as count1 FROM transactions WHERE WEEKDAY(datetime) = 5 
AND branchid = 'branch2')
于 2012-05-02T13:27:48.127 回答
2

有几种方法可以做到这一点。使用UNION已有的,您可以围绕子查询构建数据透视查询。name此版本为原始 UNION 中的每个列添加一个静态,并使用它们来区分CASE外部查询的语句。

在您的情况下,可以使用SELECT列表中的子选择来完成,但是此方法更可扩展为其他类型的透视查询,并且是实现它们的更通用约定。

SELECT 
  SUM(CASE WHEN name = 'count1' THEN counts ELSE 0 END) AS count1,
  SUM(CASE WHEN name = 'count2' THEN counts ELSE 0 END) AS count2
FROM (
   SELECT 'count1' as name, COUNT(orderid) as counts FROM transactions WHERE WEEKDAY(datetime) = 5 
     AND branchid = 'branch1' 
   UNION 
   SELECT 'count2' as name, COUNT(orderid) as counts FROM transactions WHERE WEEKDAY(datetime) = 5 
     AND branchid = 'branch2'
) subq
于 2012-05-02T13:28:11.613 回答
1

在 SELECT 部分,使用 CASE 并检查它是 branch1 还是 branch2。您可以在 SELECT 中为每个列定义单独的列。而且你不需要做一个 UNION - 你可以做一个 GROUP BY branchid WHERE branchid in ('branch1','branch2')。有道理?

于 2012-05-02T13:26:39.783 回答