我们假设每次卖家销售产品时都会有SellerId
,DateTime
,ProductType
的表格。 ProductType来自ENUM
类型,{0 =电话,1 =充值,2 = SimCard}。然后我有一张包含SellerId
和SellerName
的表格。
我想创建一个显示此视图的存储过程:
ID | NAME | Phones | Recharges | SimCards | Total
----|------|--------|-----------|----------|-------
05 | Eddy | 6 | 7 | 0 | 13
我知道如何join
这两个表在此视图中获取ID和NAME,但我不知道如何SUM
每个ProductType
进入不同的列。我还希望每个ID / NAME只有一行。
有人能告诉我如何在这个简单的例子中实现这个目标吗?
答案 0 :(得分:2)
select t1.sellerid, t1.sellername,
sum(case when ProductType = 0 then 1 end) as Phones,
sum(case when ProductType = 1 then 1 end) as Recharges,
sum(case when ProductType = 2 then 1 end) as SimCards,
count(t2.ProductType) as Total,
from table1 t1
left join table2 t2 on t1.sellerid = t2.sellerid
group by t1.sellerid, t1.sellername
答案 1 :(得分:1)
以下是使用动态PIVOT
的答案。我已经创建了一个名为#ProdType的第三个表,它包含你的枚举值...这完全是可选的,但是它更容易维护,因为你只需添加到表中添加一个列......你可以看到我分别将“案例”和“屏幕”添加为产品3/4。
/* IF TEMP TABLES EXIST, DROP THEM */
IF OBJECT_ID('tempdb..#SELLER') IS NOT NULL DROP TABLE #SELLER
IF OBJECT_ID('tempdb..#PRODTYPE') IS NOT NULL DROP TABLE #PRODTYPE
IF OBJECT_ID('tempdb..#DATA') IS NOT NULL DROP TABLE #DATA
/* SETUP TEST TABLES */
CREATE TABLE #SELLER (SELLERID INT, NAME NVARCHAR(50))
CREATE TABLE #DATA (SELLERID INT, SALEDATE DATETIME, PRODUCTTYPE INT)
INSERT INTO #SELLER (SELLERID, NAME)
VALUES (5, 'Eddy'), (6,'Dave')
INSERT INTO #DATA (SELLERID, SALEDATE, PRODUCTTYPE)
VALUES (5, GETDATE(), 0),(5, GETDATE(), 0),(5, GETDATE(), 0),(5, GETDATE(), 0),(5, GETDATE(), 0),(5, GETDATE(), 0),
(5, GETDATE(), 1),(5, GETDATE(), 1),(5, GETDATE(), 1),(5, GETDATE(), 1),(5, GETDATE(), 1),(5, GETDATE(), 1),(5, GETDATE(), 1),
(6, GETDATE(), 0)
/* MAINTAIN THIS TABLE WITH YOUR ENUM VALUES*/
CREATE TABLE #PRODTYPE (PRODUCTTYPE INT, NAME NVARCHAR(50))
INSERT INTO #PRODTYPE (PRODUCTTYPE, NAME)
VALUES (0, 'Phone'),
(1, 'Recharge'),
(2, 'SimCard'),
(3, 'Case'),
(4, 'Screen')
/* MAIN QUERY */
DECLARE @cols AS NVARCHAR(MAX),
@sql AS NVARCHAR(MAX)
SET @cols = STUFF(
(SELECT N',' + QUOTENAME(y) AS [text()]
FROM (SELECT DISTINCT NAME AS y FROM #PRODTYPE) AS Y
ORDER BY y
FOR XML PATH('')),
1, 1, N'');
SET @sql = 'SELECT SellerID, Name, '+@cols+', '+REPLACE(@cols,',','+')+' AS Total
FROM (SELECT S.SELLERID, S.NAME, P.NAME AS PTYPE
FROM #DATA D
JOIN #SELLER S ON D.SELLERID=S.SELLERID
JOIN #PRODTYPE P ON D.PRODUCTTYPE = P.PRODUCTTYPE) SUB
PIVOT (COUNT([PTYPE]) FOR PTYPE IN ('+@cols+')) AS P'
PRINT @SQL
EXEC (@SQL)