如何對資料進行合併及分組

2021-09-08 06:50:22 字數 1614 閱讀 8037

今天在論壇中被問到這樣乙個問題,就是有乙個**(格式大致如下),沒有按照正規化設計,現在想對其進行查詢,而且能進行分組彙總。

我整理乙個例子如下,對該問題進行解釋

1.建立乙個**

[日期] [datetime] null,

[幣種1] [nchar](10) null,

[金額1] [decimal](18, 0) null,

[幣種2] [nchar](10) null,

[金額2] [decimal](18, 0) null

) on [primary]

【注意】其實這個表的設計是有待改進的,不符合正規化要求

2. 新增一些資料

3. 編寫查詢語句

select 日期,幣種,sum(金額) as 小計,grouping(日期) as 日期彙總,grouping(幣種)  as 幣種彙總 from

(select 日期,幣種1 as 幣種,金額1 as 金額 from test

union all

select 日期,幣種2,金額2 from test) as p

group by 日期,幣種

with rollup

order by 日期,幣種

【注意】這裡的grouping函式是確定當前這一行出現的null值是不是因為分類彙總的原因,還是因為數值本身就是null

4. 檢視結果

5. 進一步的改造

我們甚至可以實現下面這樣的效果

是不是看起來很酷呢?查詢語法大致如下

select case when 日期彙總=1 then '全部總計' else 日期 end as 日期,

case when 幣種彙總=1 and 日期彙總=1 then '----'

when 幣種彙總=1 and 日期彙總=0 then '所有幣種小計'

else 幣種

end as 幣種,小計

from

(select top 100 percent 日期,幣種,sum(金額) as 小計,grouping(日期) as 日期彙總,grouping(幣種)  as 幣種彙總 from

(select convert(nvarchar(20),日期) as 日期,幣種1 as 幣種,金額1 as 金額 from test

union all

select convert(nvarchar(20),日期),幣種2,金額2 from test) as p

group by 日期,幣種

with rollup

order by 日期,幣種) as t

tableau用資料分組 對資料進行分組

您可以建立組以在字段中合併相關成員。例如,如果您正在使用乙個顯示各科平均考試分數的檢視,則您可能需要將某些科目分組在一起以建立科目類別。english 和 history 可合併到 liberal arts majors 組中,而 biology 和 physics 可分組為 science maj...

Pandas資料合併及分組

1 資料合併 import pandas as pd staff df pd.dataframe student df pd.dataframe print staff df print print student df pd.merge staff df,student df,how outer ...

Repeater如何對資料進行處理

最近不止乙個同學,問我在repeater裡怎麼格式化資料,怎麼處理。因為repeater 屬於伺服器端控制項。要麼利用本身的控制項事件來處理,要麼在資料來源上處理。但這樣很不方便。其實我們可以用下面2個方法 三元表示式 int.parse eval price tostring 3600 eval ...