如何将字段值作为列标题返回结果集?

时间:2012-05-02 13:23:22

标签: mysql

以下是对我所拥有内容的粗略了解:

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

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

3 个答案:

答案 0 :(得分: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')

答案 1 :(得分:2)

有几种方法可以实现这一目标。使用您已有的UNION,可以围绕子查询构建数据透视查询。此版本为原始UNION中的每个列添加静态name,并使用它们来区分外部查询上的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

答案 2 :(得分:1)

在SELECT部分​​中,使用CASE并检查它是否为branch1或branch2。您可以在SELECT中为每个列定义单独的列。并且您不需要执行UNION - 您可以在('branch1','branch2')中执行GROUP BY branchid WHERE branchid。有意义吗?