SQL取数基本语法非常简单易于上手,但是到了取数的时候,很多人还是会遇到一些困难,于是我把最近遇到的一些需求稍稍整理一下,供大家使用,如果觉得有用请点个赞吧~
选择各类商品销售额的top 1 的三种方法
method 1
'''
SELECT a.id,
a.rev,
a.contents
FROM YourTable a
INNER JOIN (
SELECT id, MAX(rev) rev --销售额
FROM YourTable
GROUP BY id
) b ON a.id = b.id AND a.rev = b.rev
'''
method 2
'''
SELECT t.*
FROM
(
SELECT id
,rev--销售额
,contents
,MAX(rev) OVER (PARTITION BY id) as max_rev
FROM YourTable
) t
WHERE t.rev = t.max_rev
'''
method 3, 这个方法适用性更广
'''
SELECT t.*
FROM
(
SELECT id
,rev--销售额
,contents
,ROW_NUMBER() OVER (PARTITION BY id ORDER BY rev DESC) rank
FROM YourTable
) t
WHERE t.rank = 1
'''
查询一列
方法一,建一张临时表,然后使用where
Create a temp table where names are stored, and then use the following query:
select * from Tags
where Name in (select distinct name from temp)
order by Count desc
方法二,使用join
使用窗口函数求累计的sum
SELECT somedate, somevalue,
SUM(somevalue) OVER(ORDER BY somedate)
AS RunningTotal
FROM Table
多行合并成一行,这个函数不一定每个数据库都有
SELECT deptno, wm_concat(‘ABCD’,ename) AS employees
FROM emp
GROUP BY deptno;
未完待续。。。
网友评论