gpt4 book ai didi

在 SELECT 中使用 FILTER 的 SQL GROUP BY

转载 作者:行者123 更新时间:2023-12-04 23:48:30 26 4
gpt4 key购买 nike

如果我有以下示例数据:

╔══════════════╦══════════════════╦════════════╦═══════╗
║ Client ║ con_id ║ mat1_07_03 ║ Ccode ║
╠══════════════╬══════════════════╬════════════╬═══════╣
║ Clients Name ║ C13109BBFD511534 ║ $1,062.00 ║ NOFL ║
║ Clients Name ║ C11AC9BBF74D6882 ║ $879.73 ║ NOFL ║
║ Clients Name ║ C12A69BBF1ACB578 ║ $2,790.29 ║ NOFA ║
║ Clients Name ║ C12A69BBF1ACB578 ║ $912.00 ║ NOFL ║
║ Clients Name ║ C6B0CA1A767C9744 ║ $2,180.11 ║ NOFL ║
║ Clients Name ║ C11AC9BBF74D6882 ║ $878.67 ║ NOFA ║
║ Clients Name ║ C13B79BBF4F1F450 ║ $300.00 ║ NOFL ║
║ Clients Name ║ C12A69BBF1ACB578 ║ $1,790.67 ║ NOFL ║
║ Clients Name ║ CA6869E2FE38A449 ║ $240.00 ║ NOFA ║
║ Clients Name ║ C46439FB0D847140 ║ $3,392.66 ║ NOFL ║
║ Clients Name ║ C12A69BBF1ACB578 ║ $1,791.73 ║ NOFA ║
║ Clients Name ║ C13B49BBF12ED236 ║ $0.00 ║ NOFL ║
║ Clients Name ║ C12A69BBF1ACB578 ║ $879.73 ║ NOFL ║
╚══════════════╩══════════════════╩════════════╩═══════╝

并应用以下查询:

SELECT 
[Client]=MAX(m.Client)
,[CaseCount]=COUNT(m.con_id)
,[AmtInDispute]=CONVERT(char, SUM(Convert(money, m.mat1_07_03)), 101)
FROM lntmu11.matter m
GROUP BY m.con_id
ORDER BY COUNT(m.Client) DESC

我如何进一步对 Ccode 列进行分组以获得 COUNT 行数NOFANOFL

我想要的输出将显示为:

╔══════════╦═══════════╦═══════════════╦═══════════════╦══════════════╗
║ Client ║ CaseCount ║ NOFACaseTotal ║ NOFLCaseTotal ║ AmtInDispute ║
╠══════════╬═══════════╬═══════════════╬═══════════════╬══════════════╣
║ Client A ║ 3548 ║ 2000 ║ 1548 ║ 5,658,307.60 ║
║ Client B ║ 3366 ║ 100 ║ 3266 ║ 2,885,649.48 ║
║ Client C ║ 3014 ║ 800 ║ 2214 ║ 2,851,507.13 ║
║ Client D ║ 2340 ║ 340 ║ 2000 ║ 3,467,207.12 ║
╚══════════╩═══════════╩═══════════════╩═══════════════╩══════════════╝

最佳答案

只需使用条件聚合:

SELECT m.Client, CaseCount = COUNT(m.con_id),
CONVERT(varchar(255), SUM(Convert(money, m.mat1_07_03)), 101) as AmtInDispute
sum(case when cCode = 'NOFA' then 1 else 0 end) as NOFACaseTotal,
sum(case when cCode = 'NOFL' then 1 else 0 end) as NOFLCaseTotal,
FROM lntmu11.matter m
GROUP BY m.client
ORDER BY COUNT(m.Client) DESC;

注意:在对字符进行转换时,始终包括长度(在 T-SQL 中)。

关于在 SELECT 中使用 FILTER 的 SQL GROUP BY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26149147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com