在SQL Server中显示上半年和下半年的销量总和以及总销量

Posted

技术标签:

【中文标题】在SQL Server中显示上半年和下半年的销量总和以及总销量【英文标题】:Display the sum of sales volume for first half and second half and total sales volume in SQL Server 【发布时间】:2016-10-16 19:06:11 【问题描述】:

我正在做一个多层次营销项目,这是我的表格结构

CREATE TABLE [Changu143Aa].[UserSalesVolume]
(
    [ID] [bigint] IDENTITY(1,1) NOT NULL,
    [UserID] [bigint] NULL,
    [PSV] [decimal](18, 2) NULL DEFAULT ((0)),
    [GSV] [decimal](18, 2) NULL DEFAULT ((0)),
    [DateAdded] [datetime] NULL,
    [Pin] [uniqueidentifier] NULL
)

如果当前日期在 1-15 日和 16-30/31 日之间(如果日期属于 16-30/),我需要显示销量,因为这是他从当月 1-15 日获得的销量总和第 31 次我写了一个查询,但它不能正常工作,任何人都可以帮助我

IF OBJECT_ID('tempdb..#TPersonalSalesVol') IS NOT NULL
    DROP TABLE #TPersonalSalesVol

IF OBJECT_ID('tempdb..#MPersonalSalesVol') IS NOT NULL
    DROP TABLE #MPersonalSalesVol

CREATE TABLE #TPersonalSalesVol 
(
     TotalPSV Decimal(18, 2),
     TotalGSV Decimal(18, 2), 
     PSV Decimal(18, 2),
     GSV Decimal(18, 2), 
     MUserID bigint 
)

CREATE TABLE #MPersonalSalesVol 
(
     PSV Decimal(18, 2),
     GSV Decimal(18, 2), 
     MUserID bigINT 
)

INSERT INTO #MPersonalSalesVol (PSV, GSV, MUserID)
    SELECT
        SUM(at.PersonalSalesVolume) as PSV, 
        SUM(at.GroupSalesVolume) as GSV,at.UserID
    FROM 
        UserSalesVolume AS at 
    WHERE
        DATEPART(month,DateAdded) = DATEPART(month,GetDate())
        AND DATEPART(day,DateAdded)/16 = DATEPART(day,GetDate())/16
    GROUP BY 
        at.UserID, CONVERT(DATE, at.DateAdded, 101)

INSERT INTO #TPersonalSalesVol (TotalPSV, TotalGSV, PSV, GSV, MUserID)
    SELECT
        SUM(at.PersonalSalesVolume) as TotalPSV, 
        SUM(at.GroupSalesVolume) as TotalGSV,
        t.PSV, t.GSV, at.UserID 
    FROM
        #MPersonalSalesVol AS t 
    JOIN
        UserSalesVolume AS at ON at.UserID = t.MUserID
    GROUP BY
        at.UserID, t.PSV, t.GSV

SELECT * 
FROM #TPersonalSalesVol

【问题讨论】:

存储过程对你有用吗? 【参考方案1】:

声明 @CurDate datetime2(7) = '2016-10-16' 声明 @Year int = YEAR(@CurDate) 声明 @Month int = MONTH(@CurDate) -- 计算日范围 DECLARE @StartDay int = CASE WHEN DAY(@CurDate) DECLARE @EndDay int = CASE WHEN(@CurDate)

选择用户 ID、SUM(PSV)、SUM(GSV)

来自用户销售量

WHERE YEAR(DateAdded) = @Year AND MONTH(DateAdded) = @Month AND DAY(DateAdded) BETWEEN @StartDay AND @EndDay

按用户 ID 分组

【讨论】:

以上是关于在SQL Server中显示上半年和下半年的销量总和以及总销量的主要内容,如果未能解决你的问题,请参考以下文章

国产手机还是干不过苹果,iPhone12上市半年销量破亿

芯片短缺加剧,上半年汽车销量逆势上涨的丰田也扛不住了,9月减产40%

NFT265发布上半年NFT行业报告,NFT项目总融资额超过10亿美元

廉价的磷酸铁锂获热捧,可惜行业龙头比亚迪从中获益太少

销量主导,手机产业迎新节点

Apple简讯:第六代iPad mini推迟至今年下半年发布