请帮帮我,我想问一下如何计算群组使用SQL服务器语法。样本是这样的:
Table : Leasing
Field : LeasingName
Data : - PANIN
- CLIPAN
- MEGA
etc
Table : Insurance
Field : InsuranceName
Data : - BUANA
- MUGI
- BESS
etc
Table Customer
NoCust LeasingName InsuranceName --> Field Name
00001 PANIN
00002 PANIN BESS
00003 MEGA BUANA
00004 CLIPAN MUGI
我想要的结果是:
我想按组租赁名称和保险名称选择并计算所有数据表:保险和租赁
所以结果可能是这样的:
| PANIN | CLIPAN | MEGA | --> All data from table Leasing
2 1 1
| BUANA | MUGI | BESS | --> All Data from table Insurance
1 1 1
所有结果计数都来自表客户的计数 请帮我。
答案 0 :(得分:1)
Use PIVOT Table to get your result :
CREATE TABLE #CustomerTable (NoCust INT , LeasingName VARCHAR(100) ,
InsuranceName VARCHAR(100))
INSERT INTO #CustomerTable (NoCust , LeasingName , InsuranceName )
SELECT 00001,'PANIN','' UNION ALL
SELECT 00002,'PANIN','BESS' UNION ALL
SELECT 00003,'MEGA','BUANA' UNION ALL
SELECT 00004,'CLIPAN','MUGI'
SELECT CLIPAN , MEGA , PANIN
FROM
(
SELECT LeasingName , COUNT(*) Cnt
FROM #CustomerTable
GROUP BY LeasingName
) A
PIVOT
(
MAX(Cnt) FOR LeasingName IN ([CLIPAN],[MEGA],[PANIN])
)pvt
SELECT [BESS],[BUANA],[MUGI]
FROM
(
SELECT InsuranceName , COUNT(*) Cnt
FROM #CustomerTable
GROUP BY InsuranceName
) A
PIVOT
(
MAX(Cnt) FOR InsuranceName IN ([BESS],[BUANA],[MUGI])
)pvt
答案 1 :(得分:0)
select
count( * ) RecordsPerGroup,
COUNT( * ) OVER () AS TotalRecords
from temptable
group by column_1, column_2, column_3, column_4