Sql Select语句,该语句在各自的列中排列条件
这可能很简单,但我已经浏览了文档,无法理解。以下是源表:Sql Select语句,该语句在各自的列中排列条件,sql,select,sum,sas,Sql,Select,Sum,Sas,这可能很简单,但我已经浏览了文档,无法理解。以下是源表: store item date sales 101 00001 27-Oct-12 1 101 00002 27-Oct-12 0 102 00001 27-Oct-12 2 102 00002 27-Oct-12 1 101 00001 3-Nov-12 0 101 00002 3-Nov-12 0 102 00001 3-Nov-12 1 102
store item date sales
101 00001 27-Oct-12 1
101 00002 27-Oct-12 0
102 00001 27-Oct-12 2
102 00002 27-Oct-12 1
101 00001 3-Nov-12 0
101 00002 3-Nov-12 0
102 00001 3-Nov-12 1
102 00002 3-Nov-12 1
…我正试图编写一个查询,最终得到一个月销售额表,商店有自己的列,比如说,只有商品#00001--
这是我试过的代码--
感谢任何帮助;谢谢 您很接近,不需要
groupby
聚合,也不确定MySQL是否允许在groupby
中使用别名:
select year(date) as SalesYear,
month(date) as SalesMonth,
sum(case when store in (101) then sales else 0 end) as store101sales,
sum(case when store in (102,103) then sales else 0 end) as otherstoresales
from source_table
where item=00001;
GROUP BY year(date), month(date)
ORDER BY SalesYear, SalesMonth, store101sales, otherstoresales;
非常感谢大家,;但它仍然不起作用。以下是我得到的错误:错误:对表/相关名称sales的未解析引用。错误:未解析对表/关联名称sales的引用。错误:WHEN子句2的结果与前面的结果的数据类型不同。错误:SUM summary函数需要一个数值参数。错误:WHEN子句2的结果与前面的结果的数据类型不同。错误:SUM summary函数需要一个数字参数。啊,没有注意,。您有
sales.count
,它将引用一个名为sales
的表中的字段count
,因此我相信上面的更新应该可以做到。太棒了!我曾经想象过,要想得到总额,需要参考销售对象的某种计数方法。再次感谢您抽出时间帮助我提高SQL读写能力。没问题,如果您确实想要一个计数而不是字段的总和,您可以使用sum(CASE WHEN criteria than 1 END)
,它将作为该情况下的计数。
select distinct
year(date) as SalesYear,
month(date) as SalesMonth,
sum(case when store in (101) then sales.count else 0 end) as store101sales,
sum(case when store in (102,103) then sales.count else 0 end) as otherstoresales,
from source_table
where item=00001;
GROUP BY SalesYear, SalesMonth, store101sales, otherstoresales,
ORDER BY SalesYear, SalesMonth, store101sales, otherstoresales;
select year(date) as SalesYear,
month(date) as SalesMonth,
sum(case when store in (101) then sales else 0 end) as store101sales,
sum(case when store in (102,103) then sales else 0 end) as otherstoresales
from source_table
where item=00001;
GROUP BY year(date), month(date)
ORDER BY SalesYear, SalesMonth, store101sales, otherstoresales;