日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

分组查询一例

發布時間:2025/5/22 编程问答 13 豆豆
生活随笔 收集整理的這篇文章主要介紹了 分组查询一例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在分組查詢的select列表里面列只能為groupby里面的列,否則只能放在聚合函數里面。那么查詢出來的信息就不完整,下面通過下面該查詢讓更多的列被查詢出來。

?

input為商品入庫表,total為數量,unitprice為單價,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)

?

?

現在要查詢的是每一種商品最后一次入庫的單價,以及該種商品的總和。

先看看兩個表的數據先:

可用通過以下查詢實現:

代碼 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

?

下面來分解一下該查詢:

1.因為兩個表有主外鍵關系,所以通過聯合查詢,把兩張表合二為一。

select?i.id,ic.productname,i.unitprice,i.total?
from?input?as?i,input_categories?as?ic?where?i.product_id=ic.id

2.然后進行分組統計

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了,為了讓更多的信息包涵進來和可以進行一次連接查詢(步驟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.通過row_number()來插入一個序列。

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.最后,搞定最后一次入庫的單價,id最大的ran剛好為1,所以篩選一下ran=1的記錄就OK了。

大功告成拉,oh yeah!!

轉載于:https://www.cnblogs.com/Fskjb/archive/2010/02/28/1675240.html

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的分组查询一例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。