我是一个相对较新的SQL,并试图通过一个简单的查询来查看今年的销售额与去年同一天或同一天的理想情况相同。
我创建了以下基于单个设置日的查询。我需要移动它才能真正得到今天的日期,但是我想以后会解决这个问题。
-
Below is the query
-strtrdecode = store location
-dtmtradedate = transaction date
-cursales = sales value
-Target = will contain Targets but i haven't generated any yet but need to show -the field
有人请告诉我如何显示今年和去年的数据请在每家商店的同一行上显示
即
liverpool, 01/06/2015, 4000,3000
blackpool, 01/06/2015, 6000, 7500 etc..
提前谢谢
麦克
TABLE_CATALOG TABLE_SCHEMA TABLE_NAME COLUMN_NAME
> DRSData dbo DAILYSALES STRSALETYPE
> DRSData dbo DAILYSALES STRTRADECODE
> DRSData dbo DAILYSALES CURSALES
> DRSData dbo DAILYSALES DTMTRADEDATE
> DRSData dbo DAILYSALES INTTRANSNUM
*SELECT strtradecode, dtmtradedate, sum(cursales) as [Actual SALES TY], '' as Target
FROM DAILYSALES
where (STRSALETYPE = 'H' )and (DTMTRADEDATE BETWEEN CONVERT(DATETIME, '2015-06-01 00:00:00', 102) AND CONVERT(DATETIME, '2015-06-01 00:00:00',
102))
group by strtradecode, dtmtradedate*
答案 0 :(得分:0)
好的,请耐心等待,因为这是我第一次尝试答案,而且我对SQL也很陌生。
我正在尝试学习,但我想更多地参与其中。我确信这不是执行你想做的最有效的方式,但就像我说我很新,这是我知道的唯一方式。我完全愿意接受纠正和帮助。谢谢!
-- 1. Began by declaring the dates.
-- 2. Then created a temp table.
-- 3. Inserted into the temp table
-- 4. Created JOINS to separate the dates you wanted.
-- 5. SELECTED fields from the temp table for the desired output.
-- Step 1
DECLARE @startDate1 DATETIME2 = '01/01/2014', -- Creating previous year
@endDate1 DATETIME2 = '12/31/2014', -- Creating previous year
@startDate2 DATETIME2 = '01/01/2015', -- Creating this year
@endDate2 DATETIME2 = '12/31/2015'; -- Creating this year
-- Step 2
DECLARE @yearFigures TABLE ( -- Created temp table with your desired output
StoreLocation VARCHAR(20),
TransactionDt VARCHAR(10),
PreviousYear VARCHAR(20),
CurrentYear VARCHAR(20))
-- Step 3
INSERT INTO @yearFigures -- Inserting into your temp table
SELECT DISTINCT
strtrdecode,
CONVERT( VARCHAR(10), dtmtradedate, 101),
sales1.cs1,
sales2.cs2
FROM DAILYSALES dls
-- Step 4
LEFT OUTER JOIN(
SELECT cursales AS cs1
FROM DAILYSALES dls
WHERE dtmtradedate BETWEEN @startDate1 AND @endDate1
GROUP BY cursales ) AS sales1 ON sales1.cursales = dls.cursales -- Year one
LEFT OUTER JOIN (
SELECT cursales AS cs2
FROM DAILYSALES dls
WHERE dtmtradedate BETWEEN @startDate2 AND @endDate2
GROUP BY cursales ) AS sales2 ON sales2.cursales = dls.cursales; -- Year two
-- Step 5
SELECT StoreLocation,
TransactionDt,
SalesValue,
SalesValue2
FROM @yearFigures -- From here you're pulling from your temp table (your output)
你应该得到你想要的东西。 LEFT OUTER JOIN分隔销售价值年份并命名它们。我在我的一个dbo上运行了一行并得到了这个
StoreLocation TransactionDt PreviousYear CurrentYear
AESKAGGS 03/14/2014 828.35 400.00
再次对我说话很容易..我是个菜鸟。