分组查询一例
在分組查詢的select列表里面列只能為groupby里面的列,否則只能放在聚合函數(shù)里面。那么查詢出來(lái)的信息就不完整,下面通過(guò)下面該查詢讓更多的列被查詢出來(lái)。
?
input為商品入庫(kù)表,total為數(shù)量,unitprice為單價(jià),product_id為外鍵引用自input_categories表
CREATE?TABLE?[dbo].[input](????[id]?[int]?IDENTITY(1,1)?NOT?NULL,
????[product_id]?[int]?NOT?NULL,
????[unitprice]?[float]?NULL,
????[total]?[int]?NULL,
?
input_categories位商品表(productname為商品名稱):
CREATE?TABLE?[dbo].[input_categories](????[id]?[int]?IDENTITY(1,1)?NOT?NULL,
????[productname]?[nvarchar](50)?NOT?NULL)
?
?
現(xiàn)在要查詢的是每一種商品最后一次入庫(kù)的單價(jià),以及該種商品的總和。
先看看兩個(gè)表的數(shù)據(jù)先:
可用通過(guò)以下查詢實(shí)現(xiàn):
代碼 select?*?from(
select?*,ran=row_number()?over(partition?by?productname?order?by?id?desc)
from
(select?c.id,b.productname,b.total,c.unitprice?from
(select?productname,sum(total)?as?total?from
(select?i.id,ic.productname,i.unitprice,i.total?
from?input?as?i,input_categories?as?ic?where?i.product_id=ic.id)?t
group?by?productname)?b,(select?i.id,ic.productname,i.unitprice,i.total?
from?input?as?i,input_categories?as?ic?where?i.product_id=ic.id)?c
where?b.productname=c.productname)?h
)g
where?g.ran<=1
?
下面來(lái)分解一下該查詢:
1.因?yàn)閮蓚€(gè)表有主外鍵關(guān)系,所以通過(guò)聯(lián)合查詢,把兩張表合二為一。
select?i.id,ic.productname,i.unitprice,i.total?
from?input?as?i,input_categories?as?ic?where?i.product_id=ic.id
2.然后進(jìn)行分組統(tǒng)計(jì)
select?productname,sum(total)?as?total?from
(select?i.id,ic.productname,i.unitprice,i.total?
from?input?as?i,input_categories?as?ic?where?i.product_id=ic.id)?t
group?by?productname
3.分組后信息只剩下productname,total了,為了讓更多的信息包涵進(jìn)來(lái)和可以進(jìn)行一次連接查詢(步驟2和步驟1的連接查詢)
select?c.id,b.productname,b.total,c.unitprice?from
(select?productname,sum(total)?as?total?from
(select?i.id,ic.productname,i.unitprice,i.total?
from?input?as?i,input_categories?as?ic?where?i.product_id=ic.id)?t
group?by?productname)?b,(select?i.id,ic.productname,i.unitprice,i.total?
from?input?as?i,input_categories?as?ic?where?i.product_id=ic.id)?c
where?b.productname=c.productname
4.通過(guò)row_number()來(lái)插入一個(gè)序列。
select?*,ran=row_number()?over(partition?by?productname?order?by?id?desc)
from
(select?c.id,b.productname,b.total,c.unitprice?from
(select?productname,sum(total)?as?total?from
(select?i.id,ic.productname,i.unitprice,i.total?
from?input?as?i,input_categories?as?ic?where?i.product_id=ic.id)?t
group?by?productname)?b,(select?i.id,ic.productname,i.unitprice,i.total?
from?input?as?i,input_categories?as?ic?where?i.product_id=ic.id)?c
where?b.productname=c.productname)?h
)g
5.最后,搞定最后一次入庫(kù)的單價(jià),id最大的ran剛好為1,所以篩選一下ran=1的記錄就OK了。
大功告成拉,oh yeah!!
轉(zhuǎn)載于:https://www.cnblogs.com/Fskjb/archive/2010/02/28/1675240.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
- 上一篇: 【转】 LINQ TO SQL中的sel
- 下一篇: asp多重查询的解决方案