我有一个SQL查询,提供品牌名称和订单计数(案例1)。
我必须准备一份每小时的报告,但如果我没有为任何品牌计算一小时,则不会显示特定品牌(案例-2)。
在这种情况下,我如何在警报邮件中自动填充brand2?
示例SQL
SELECT distinct(brand), count(*) Hourly Count
FROM table_name where date_time between systimestamp-1/24 and systimestamp
GROUP BY brand;
答案 0 :(得分:0)
首先,几乎不需要使用select distinct
和group by
(当然,在这种情况下,一列不必要地被括号括起来)并且显示对两种结构都缺乏了解。
执行所需操作的一种方法是使用条件聚合:
SELECT brand,
SUM(CASE WHEN date_time between systimestamp-1/24 and systimestamp THEN 1 ELSE 0 END) as HourlyCount
FROM table_name
GROUP BY brand;
另一种方法假设您有一个包含所有品牌的表格:
SELECT b.brand, count(t.brand) as HourlyCount
FROM brands b LEFT JOIN
table_name
ON b.brand = t.brand AND
t.date_time between systimestamp-1/24 and systimestamp
GROUP BY b.brand;
答案 1 :(得分:0)
请找到我想要的内容。
SELECT DISTINCT(BRAND_NAME),SUM(COUNT)FROM(
SELECT distinct(BRAND_NAME) ,count(*) COUNT
FROM TABLE
UNION ALL
SELECT BRAND_NAME,0 AS COUNT
FROM (SELECT 'Brand1' AS BRAND_NAME FROM DUAL
UNION ALL
SELECT 'Brand2' AS BRAND_NAME FROM DUAL
UNION ALL
SELECT 'Brand3' AS BRAND_NAME FROM DUAL)
TEMP1)
TEMP2
GROUP BY BRAND_NAME
ORDER BY 1;