如何在SQL select语句中选择组合类别名称?

时间:2017-11-08 05:18:08

标签: mysql heidisql

我有一个select语句如下:

SELECT 
  sales.Added_by as "Added_By",
  CONCAT(HOUR(sales.Sales_Date), ':00-', HOUR(sales.Sales_Date)+2, ':00') AS Hours,
  COUNT(sales.Sales_ID) AS `Sales_ID`,
  sum(sales.Quantity) as "Quantity",
  sum(sales.Tax_Amount) as "Tax_Amount",
  sum(sales.Discount_Amount) as "Discount_Amount",
  sum(sales.Total_Price) as "Total_Price",
  sum(sales.Cash) as "Cash",
  sum(sales.Change) as "Change",
  MAX(sales_detail.Category_ID) as "Category_ID",
  MAX(sales_detail.Stock_Name) as "Stock_Name",
  categories.Category_Name
FROM sales
  inner join sales_detail on sales.Sales_Number=sales_detail.Sales_Number
  inner join categories on categories.Category_ID = sales_detail.Category_ID
GROUP BY HOUR(sales.Sales_Date) asc, sales.Added_By asc 

我的问题是如何在

中添加类别的名称
MAX(sales_detail.Category_ID) as "Category_ID"

列?输出应该像1 - Category A

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

一种hackish方式,特定于mysql使用GROUP_CONCAT以降序排序按类别ID排序的每个组的逗号分隔类别列表,然后使用SUBSTRING_INDEX字符串函数来选择第一个值

SUBSTRING_INDEX(
     GROUP_CONCAT(categories.name ORDER BY categories.Category_ID DESC)
,',',1) "Category_Name",
  

但是我如何一起添加到_id栏类

CONCAT( MAX(sales_detail.Category_ID),
        '-', 
       SUBSTRING_INDEX(
          GROUP_CONCAT(categories.name ORDER BY categories.Category_ID DESC)
       ,',',1)
) AS "Category"

答案 1 :(得分:0)

如果您的类别名称对于组合在一起的所有行始终相同,则只需将categories.Category_Name添加到GROUP BY子句中,并像往常一样连接列名称:

SELECT 
  sales.Added_by as "Added_By",
  CONCAT(HOUR(sales.Sales_Date), ':00-', HOUR(sales.Sales_Date)+2, ':00') AS Hours,
  COUNT(sales.Sales_ID) AS `Sales_ID`,
  sum(sales.Quantity) as "Quantity",
  sum(sales.Tax_Amount) as "Tax_Amount",
  sum(sales.Discount_Amount) as "Discount_Amount",
  sum(sales.Total_Price) as "Total_Price",
  sum(sales.Cash) as "Cash",
  sum(sales.Change) as "Change",
  MAX(sales_detail.Category_ID) || ' - ' || categories.Category_Name as "Category_ID",
  MAX(sales_detail.Stock_Name) as "Stock_Name",
  categories.Category_Name
FROM sales
  inner join sales_detail on sales.Sales_Number=sales_detail.Sales_Number
  inner join categories on categories.Category_ID = sales_detail.Category_ID
GROUP BY HOUR(sales.Sales_Date) asc, sales.Added_By asc, categories.Category_Name