Grouping with pivot to get count by week - sql-server

I Have a table temp_customer. Schema and some data like below-
CREATE TABLE [dbo].[temp_customer](
[id] [int] IDENTITY(1,1) NOT NULL,
[company_id] [int] NOT NULL,
[created_by] [int] NULL,
[created_at] [datetime] NULL,
[code] [varchar](25) NOT NULL,
[name] [varchar](50) NULL,
)
SET IDENTITY_INSERT [dbo].[temp_customer] ON
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1714, 1, 1, CAST(N'2018-02-14 11:43:00.757' AS DateTime), N'STET-00001', N'Stephan Taylor')
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1715, 1, 1, CAST(N'2018-02-14 11:43:01.007' AS DateTime), N'TAMJ-00001', N'Tamala Jones')
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1716, 1, 2, CAST(N'2018-02-14 11:43:01.457' AS DateTime), N'TARB-00001', N'Taran Blauman')
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1718, 1, 1, CAST(N'2019-01-29 00:00:00.000' AS DateTime), N'VERD-00001', N'Veronica Dave')
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1719, 1, 1, CAST(N'2018-02-14 11:43:02.190' AS DateTime), N'WAYD-00001', N'Wayne Dotson')
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1720, 1, 2, CAST(N'2018-03-12 07:40:34.107' AS DateTime), N'LARJ-00001', N'Larry Jacobs')
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1721, 1, 2, CAST(N'2018-03-28 03:40:52.673' AS DateTime), N'ROBM-00002', N'Robert Matte')
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1722, 1, 1, CAST(N'2018-03-28 05:09:53.093' AS DateTime), N'MART-00001', N'Mark Taylor')
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1723, 1, 1, CAST(N'2018-03-28 05:39:19.237' AS DateTime), N'TAYT-00001', N'ALEX BRUZZI')
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1724, 1, 3, CAST(N'2018-04-04 04:37:29.547' AS DateTime), N'STOCK', N'STOCK')
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1725, 1, 3, CAST(N'2018-04-04 06:51:10.797' AS DateTime), N'AMAT-00001', N'Amanda Trezza')
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1726, 1, 1, CAST(N'2018-04-04 06:55:04.720' AS DateTime), N'ADRG-00001', N'Adriana Grande')
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1727, 1, 3, CAST(N'2018-04-05 00:00:00.000' AS DateTime), N'ISSJ-00002', N'Issac Johnes')
INSERT [dbo].[temp_customer] ([id], [company_id], [created_by], [created_at], [code], [name]) VALUES (1728, 1, 2, CAST(N'2019-01-18 00:00:00.000' AS DateTime), N'JACJ-00001', N'Jacob Jensen')
it looks like -
I would like to get output group on created_by with total_customer_created and week in which customer created as individual columns. eg in excel like -
i.e on basis of Week(starting from monday) , total customer created by 1,2,3..... etc in required date range.
Any helps appreciated in advance.

I have found one solution, it is working.
firstly a function to find weeks(with date range)
CREATE FUNCTION [dbo].[fGetWeeksList]
(
#StartDate DATETIME
,#EndDate DATETIME
)
RETURNS
TABLE
AS
RETURN
(
SELECT DATEADD(DAY,-(DATEPART(DW,DATEADD(WEEK, x.number, #StartDate))-2),DATEADD(WEEK, x.number, #StartDate)) as [StartDate]
,DATEADD(DAY,-(DATEPART(DW,DATEADD(WEEK, x.number + 1, #StartDate))-1) ,DATEADD(WEEK, x.number + 1, #StartDate)) AS [EndDate]
FROM master.dbo.spt_values x
WHERE x.type = 'P' AND x.number <= DATEDIFF(WEEK, #StartDate, DATEADD(WEEK,0,CAST(#EndDate AS DATE)))
)
And then use it in below query
select cast(cast(fGetWeeksList.startdate as date) as varchar(max)) + ' To '+cast(cast(fGetWeeksList.enddate as date) as varchar(max)) as week_range,
*
into #week_table from fGetWeeksList('01-01-2022','06-02-2022')
select users.user_cd ,
users.first_name ,
users.last_name,
count(customers.id) cust_count,
#week_table.week_range
into #cust_count
from users
inner join customers on
users.id = customers.created_by
inner join #week_table on
cast(customers.created_at as date) between #week_table.StartDate and #week_table.EndDate
group by
users.user_cd ,users.first_name ,users.last_name,
#week_table.week_range
DECLARE #columns NVARCHAR(MAX), #sql NVARCHAR(MAX);
SET #columns = N'';
SELECT #columns += N', ' + QUOTENAME(week_range)
FROM (SELECT distinct #week_table.week_range FROM #week_table
GROUP BY #week_table.week_range) AS x;
print #columns
SET #sql = N'SELECT user_cd,p.first_name,p.last_name, ' + STUFF(#columns, 1, 2, '') + '
FROM
(
SELECT p.week_range, p.user_cd,p.first_name,p.last_name, p.cust_count FROM dbo.#cust_count AS p
) AS j
PIVOT
(
SUM(cust_count) FOR week_range IN ('+ STUFF(REPLACE(#columns, ', p.[', ',['), 1, 1, '') + ')
) AS p;';
PRINT #sql;
EXEC sp_executesql #sql;
drop table #week_table
drop table #cust_count

Related

Select all of the files which are not parents to any other file SQL

CREATE TABLE Files (
Id INT PRIMARY KEY,
[Name] NVARCHAR(100) NOT NULL,
Size DECIMAL(18, 2) NOT NULL,
ParentId INT NULL FOREIGN KEY REFERENCES Files(Id)
)
SET IDENTITY_INSERT [dbo].[Files] ON
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (1, N'Trade.idk', CAST(2598.00 AS Decimal(18, 2)), 1, 1)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (2, N'menu.net', CAST(9238.31 AS Decimal(18, 2)), 2, 2)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (3, N'Administrate.soshy', CAST(1246.93 AS Decimal(18, 2)), 3, 3)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (4, N'Controller.php', CAST(7353.15 AS Decimal(18, 2)), 4, 4)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (5, N'Find.java', CAST(9957.86 AS Decimal(18, 2)), 5, 5)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (6, N'Controller.json', CAST(14034.87 AS Decimal(18, 2)), 3, 6)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (7, N'Operate.xix', CAST(7662.92 AS Decimal(18, 2)), 7, 7)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (8, N'file.sick', CAST(10548.35 AS Decimal(18, 2)), 8, 8)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (9, N'config.dd', CAST(8745.77 AS Decimal(18, 2)), 9, 9)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (10, N'Index.java', CAST(6121.35 AS Decimal(18, 2)), 10, 10)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (11, N'compile.ivory', CAST(1185.04 AS Decimal(18, 2)), 11, 1)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (12, N'Model.MD', CAST(4753.67 AS Decimal(18, 2)), 3, 12)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (13, N'Beat.html', CAST(907.30 AS Decimal(18, 2)), 13, 13)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (14, N'READ.img', CAST(2627.60 AS Decimal(18, 2)), 14, 7)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (15, N'Search.py', CAST(8831.43 AS Decimal(18, 2)), 15, 15)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (16, N'Controller.intro', CAST(27302.85 AS Decimal(18, 2)), 11, 1)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (17, N'Login.html', CAST(2863.23 AS Decimal(18, 2)), 16, 17)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (18, N'Administrate.go', CAST(24612.57 AS Decimal(18, 2)), 9, 18)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (19, N'READ.html', CAST(2396.47 AS Decimal(18, 2)), 8, 1)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (20, N'index.net', CAST(9261.71 AS Decimal(18, 2)), 20, 20)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (21, N'Index.class', CAST(4001.15 AS Decimal(18, 2)), 21, 21)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (22, N'config.json', CAST(6049.09 AS Decimal(18, 2)), 22, 22)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (23, N'pipeline.dd', CAST(18407.72 AS Decimal(18, 2)), NULL, 19)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (24, N'Accelerate.dd', CAST(23042.88 AS Decimal(18, 2)), 24, 19)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (25, N'Database.dd', CAST(14905.56 AS Decimal(18, 2)), NULL, 25)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (26, N'Login.db', CAST(8015.83 AS Decimal(18, 2)), NULL, 21)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (27, N'Beat.bat', CAST(21431.98 AS Decimal(18, 2)), 25, 12)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (28, N'Jason.txt', CAST(10317.54 AS Decimal(18, 2)), NULL, 28)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (29, N'Jason.exe', CAST(28209.18 AS Decimal(18, 2)), 8, 25)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (30, N'Accelerate.idk', CAST(5520.30 AS Decimal(18, 2)), 30, 1)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (31, N'file.txt', CAST(5514.02 AS Decimal(18, 2)), 27, 1)
GO
INSERT [dbo].[Files] ([Id], [Name], [Size], [ParentId], [CommitId]) VALUES (32, N'Music.jpg', CAST(917.75 AS Decimal(18, 2)), 1, 3)
GO
SET IDENTITY_INSERT [dbo].[Files] OFF
GO
I am trying to select all of the files which are NOT a parent to any other file. This was my try:
SELECT f.Id, f.[Name], CONCAT(f.Size, 'KB') AS Size
FROM Files f
WHERE f.Id NOT IN
(SELECT f1.ParentId
FROM Files f1
WHERE f1.ParentId IS NOT NULL)
ORDER BY f.Id, f.[Name], Size DESC
Now I am trying to use joins to solve the same task.
SELECT *
FROM Files f
JOIN Files f1 ON f.ParentId = f1.Id
I am confused. When we use INNER JOIN, we get only the records where f.ParentId is not null. Can you help me? Some explanation will also be appreciated. Thank you in advance!
You could try with NOT EXISTS
This returns all rows that don't match the specified set in the not exists expression.
SELECT *
FROM Files f1
WHERE NOT EXISTS (
SELECT 1
FROM Files f2
WHERE f2.ParentId = f1.Id
)
SQLFiddle
SELECT *
FROM Files AS f1
FULL OUTER JOIN Files as f2
ON f1.ParentId = f2.Id
WHERE f1.Id IS NULL

Dynamic pivot and initialization with a constant (without sum)

I have two Tables: TbOrder and TbProduct. These tables are correlated by a condition on a number progression through the '&' operator. If the condition is true I should assign the product to the relative order.
CREATE TABLE [dbo].[TbOrder](
[Id] [bigint] NOT NULL,
[Flag] [bigint] NOT NULL,
CONSTRAINT [PK_TbOrder] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TbProduct](
[Id] [bigint] NOT NULL,
[Flag] [bigint] NOT NULL,
[Name] [varchar](50) NOT NULL,
CONSTRAINT [PK_TbProduct] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[TbOrder] ([Id], [Flag]) VALUES (1, 5124)
INSERT [dbo].[TbOrder] ([Id], [Flag]) VALUES (2, 10507925)
INSERT [dbo].[TbOrder] ([Id], [Flag]) VALUES (3, 10053569)
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (1, 4, N'Prod1')
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (2, 1024, N'Prod2')
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (3, 4096, N'Prod3')
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (4, 2, N'Prod4')
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (5, 1, N'Prod5')
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (6, 8, N'Prod6')
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (7, 512, N'Prod7')
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (8, 32, N'Prod8')
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (9, 16, N'Prod9')
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (10, 128, N'Prod10')
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (11, 64, N'Prod11')
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (12, 1, N'Prod12')
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (13, 8192, N'Prod13')
INSERT [dbo].[TbProduct] ([Id], [Flag], [Name]) VALUES (14, 16384, N'Prod14')
The query and the result are as follow:
select o.Id OrderId, o.Flag OrderFlag, p.Id ProductId,
p.Flag ProductFlag, p.Name ProductName from TbOrder o
inner join TbProduct p on (o.Flag & p.Flag)=p.Flag
I tried with Pivot but the result compared to the first query remained unchanged (removing the line --'x').
select * from
(select o.Id OrderId, o.Flag OrderFlag, p.Id ProductId, p.Flag ProductFlag, p.Name ProductName from TbOrder o
inner join TbProduct p on (o.Flag & p.Flag)=p.Flag) t
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols += QUOTENAME(Name) + ','
FROM TbProduct
ORDER BY FLAG;
SET #cols = LEFT(#cols, LEN(#cols) - 1);
print #cols;
SELECT #query = '
SELECT t.* FROM t
PIVOT
(
--'x'
FOR t.Name IN( ' + #cols + ' )
) AS pivot_table; ';
execute(#query)
What I would like obtain instead is a single row for each order and only the product name for which the condition is true (marked with an 'x' in the order row) are columns.
I thank in advance anyone who tries to solve this.
Using your transform query, you found out allProducts and allOrders. Then you can generate all combinations using CROSS JOIN.
Now you try to match each combination with the data already on transfrom, for every match you assign X.
Now with that data you can do a DINAMIC PIVOT. I skip because looks like you know how to do it.
SQL DEMO
WITH transform as (
select o.Id OrderId, o.Flag OrderFlag, p.Id ProductId,
p.Flag ProductFlag, p.Name ProductName
from TbOrder o
inner join TbProduct p
on (o.Flag & p.Flag) = p.Flag
), allProducts as (
SELECT distinct ProductName
FROM transform
), allOrders as (
SELECT distinct OrderFlag
FROM transform
)
SELECT O.OrderFlag,
P.ProductName,
CASE WHEN T.ProductName IS NOT NULL
THEN 'X'
END as flag
INTO partial_result
FROM allProducts P
CROSS JOIN allOrders O
LEFT JOIN transform T
ON O.OrderFlag = T.OrderFlag
AND P.ProductName= T.ProductName;
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.ProductName)
FROM partial_result c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #query = 'SELECT OrderFlag, ' + #cols + ' from
(
select OrderFlag
, ProductName
, flag
from partial_result
) x
pivot
(
max(flag)
for ProductName in (' + #cols + ')
) p ';
execute(#query);
OUTPUT

emp logindetails based on conditions in sql server

I have a question about SQL Server. Please tell me how to solve login and logout time calculation in SQL Server based on conditions.
If the same empid works multiple shifts, multiple shifts calculation for same date must be time difference is 5 hours then that date consider as multiple shifts for that emp
OnFloor time how much time they spent
OffFloor time how much time they spent
Sample input data :
CREATE TABLE [dbo].[emp](
[Emp Id] [float] NULL,
[Area Of Access] [nvarchar](255) NULL,
[Time] [datetime] NULL,
[floor] [nvarchar](255) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[emp] ([Emp Id], [Area Of Access], [Time], [floor]) VALUES (10, N'IN', CAST(N'2018-03-03T03:36:58.000' AS DateTime), N'Common Area')
GO
INSERT [dbo].[emp] ([Emp Id], [Area Of Access], [Time], [floor]) VALUES (10, N'OUT', CAST(N'2018-03-03T03:38:55.000' AS DateTime), N'Common Area')
GO
INSERT [dbo].[emp] ([Emp Id], [Area Of Access], [Time], [floor]) VALUES (10, N'OUT', CAST(N'2018-03-05T18:54:00.000' AS DateTime), N'Common Area')
GO
INSERT [dbo].[emp] ([Emp Id], [Area Of Access], [Time], [floor]) VALUES (10, N'IN', CAST(N'2018-03-05T18:54:13.000' AS DateTime), N'Common Area')
GO
INSERT [dbo].[emp] ([Emp Id], [Area Of Access], [Time], [floor]) VALUES (10, N'IN', CAST(N'2018-03-05T18:54:32.000' AS DateTime), N'Common Area')
GO
INSERT [dbo].[emp] ([Emp Id], [Area Of Access], [Time], [floor]) VALUES (10, N'IN', CAST(N'2018-03-05T18:55:01.000' AS DateTime), N'Production Floor')
GO
INSERT [dbo].[emp] ([Emp Id], [Area Of Access], [Time], [floor]) VALUES (10, N'OUT', CAST(N'2018-03-05T19:58:41.000' AS DateTime), N'Production Floor')
GO
INSERT [dbo].[emp] ([Emp Id], [Area Of Access], [Time], [floor]) VALUES (20, N'IN', CAST(N'2018-02-06T16:03:08.000' AS DateTime), N'Production Floor')
GO
INSERT [dbo].[emp] ([Emp Id], [Area Of Access], [Time], [floor]) VALUES (20, N'OUT', CAST(N'2018-02-06T22:01:40.000' AS DateTime), N'Production Floor')
GO
INSERT [dbo].[emp] ([Emp Id], [Area Of Access], [Time], [floor]) VALUES (20, N'IN', CAST(N'2018-02-06T22:42:15.000' AS DateTime), N'Production Floor')
GO
INSERT [dbo].[emp] ([Emp Id], [Area Of Access], [Time], [floor]) VALUES (20, N'OUT', CAST(N'2018-02-07T00:33:19.000' AS DateTime), N'Production Floor')
GO
INSERT [dbo].[emp] ([Emp Id], [Area Of Access], [Time], [floor]) VALUES (20, N'IN', CAST(N'2018-02-07T10:13:11.000' AS DateTime), N'Production Floor')
GO
INSERT [dbo].[emp] ([Emp Id], [Area Of Access], [Time], [floor]) VALUES (20, N'OUT', CAST(N'2018-02-07T15:13:10.000' AS DateTime), N'Production Floor')
GO
Based on above data I want output like below :
I tried like below :
select
ShiftDate, ShitStartTime, ShiftEndTime
, Total_Time = right(concat('0', Total_Time / 3600), 2) + ':' + right(concat('0', Total_Time % 3600 / 60), 2) + ':' + right(concat('0', Total_Time % 60), 2)
, OnFloor = right(concat('0', OnFloor / 3600), 2) + ':' + right(concat('0', OnFloor % 3600 / 60), 2) + ':' + right(concat('0', OnFloor % 60), 2)
, OffFloor = right(concat('0', OffFloor / 3600), 2) + ':' + right(concat('0', OffFloor % 3600 / 60), 2) + ':' + right(concat('0', OffFloor % 60), 2)
, [Emp ID]
from (
select
[Emp ID], ShiftDate = cast(min(Time) as date)
, ShitStartTime = isnull( min( case when ltrim(rtrim([Area Of Access]))='in'
then
Time end ) ,'1900-01-01')
, ShiftEndTime = isnull( max( case when ltrim(rtrim([Area Of Access]))='out'
then
Time end ) ,'1900-01-01')
, Total_Time = sum(ss)
, OnFloor = sum(iif(ltrim(rtrim([Area Of Access]))='in', ss, 0))
, OffFloor = sum(iif(ltrim(rtrim([Area Of Access]))='out', ss, 0))
from (
select
*, ss = datediff(ss, Time, lead(Time) over (partition by [Emp ID], grp order by Time))
from (
select
*, grp = sum(diff) over (partition by [Emp ID] order by Time)
from (
select
*, diff = iif(datediff(mi, lag(Time) over (partition by [Emp ID] order by Time), Time) > 300
and [Area Of Access]='in'
, 1, 0)
from
emp
) t
) t
) t
group by [Emp ID], grp
) t
above query is not given expected result .
Please tell me how to wirte query to achieve this task in SQL Server

SSRS budget table joined to cases of demo data

This is probalby a simple question, but I don't fully understand what is going wrong..with the method I am using..SoI've gone back to the original two tables that need to be used. So if you can suggest how to tackle this from the outset, would be greatly appreciated.
One table is cases, that holds individual case details, with dates that can be used to calculate, how long a hire went on for and the rate applied. It has a Source ID, that it has in common with a budget table. Every case has a Source ID. The other table is budget by Source ID for each calendar month. Need to compare the actual income from the dates, and rates in cases and add them and compare, the actual against budget.
The dates used to calculate the duration is the actual start date to the actual end date, but to further complicate matters, only the days of hire in the month of interest are required to be returned. So if a hire started earlier , than the month in question, just those dates are to be compared against the budget for that month.
The only other requirement is to set the rate dependent on the name of the company, either contract rate or hire daily rate. But i tried to keep it simple as possible.
It's all demo data...
USE [AutoHires]
GO
/****** Object: Table [dbo].[tblBudget] Script Date: 22/01/2018 09:57:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblBudget](
[Ref] [int] IDENTITY(1,1) NOT NULL,
[SourceID] [int] NOT NULL,
[BudgetRevenue] [money] NULL,
[BudgetHires] [int] NULL,
[BudgetSold] [int] NULL,
[BudgetInstructions] [int] NULL,
[SourceGroup] [int] NULL,
[MonthFrom] [datetime] NULL,
[MonthTo] [datetime] NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_Budget] PRIMARY KEY CLUSTERED
(
[Ref] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[tblBudget] ON
INSERT [dbo].[tblBudget] ([Ref], [SourceID], [BudgetRevenue], [BudgetHires], [BudgetSold], [BudgetInstructions], [SourceGroup], [MonthFrom], [MonthTo], [Name]) VALUES (1, 1, 300.0000, 12, 45, 80, NULL, CAST(N'2017-12-01 00:00:00.000' AS DateTime), CAST(N'2017-12-31 00:00:00.000' AS DateTime), N'SOURCEA')
INSERT [dbo].[tblBudget] ([Ref], [SourceID], [BudgetRevenue], [BudgetHires], [BudgetSold], [BudgetInstructions], [SourceGroup], [MonthFrom], [MonthTo], [Name]) VALUES (2, 2, 400.0000, 15, 50, 90, NULL, CAST(N'2017-12-01 00:00:00.000' AS DateTime), CAST(N'2017-12-31 00:00:00.000' AS DateTime), N'SOURCEB')
INSERT [dbo].[tblBudget] ([Ref], [SourceID], [BudgetRevenue], [BudgetHires], [BudgetSold], [BudgetInstructions], [SourceGroup], [MonthFrom], [MonthTo], [Name]) VALUES (3, 3, 700.0000, 4, 6, 50, NULL, CAST(N'2017-12-01 00:00:00.000' AS DateTime), CAST(N'2017-12-31 00:00:00.000' AS DateTime), N'SOURCEH')
INSERT [dbo].[tblBudget] ([Ref], [SourceID], [BudgetRevenue], [BudgetHires], [BudgetSold], [BudgetInstructions], [SourceGroup], [MonthFrom], [MonthTo], [Name]) VALUES (4, 4, 323.0000, 6, 18, 50, NULL, CAST(N'2017-12-01 00:00:00.000' AS DateTime), CAST(N'2017-12-31 00:00:00.000' AS DateTime), N'SOURCEG')
INSERT [dbo].[tblBudget] ([Ref], [SourceID], [BudgetRevenue], [BudgetHires], [BudgetSold], [BudgetInstructions], [SourceGroup], [MonthFrom], [MonthTo], [Name]) VALUES (5, 5, 567.0000, 6, 45, 56, NULL, CAST(N'2017-12-01 00:00:00.000' AS DateTime), CAST(N'2017-12-31 00:00:00.000' AS DateTime), N'SOURCEF')
INSERT [dbo].[tblBudget] ([Ref], [SourceID], [BudgetRevenue], [BudgetHires], [BudgetSold], [BudgetInstructions], [SourceGroup], [MonthFrom], [MonthTo], [Name]) VALUES (6, 6, 566.0000, 12, 56, 67, NULL, CAST(N'2017-12-01 00:00:00.000' AS DateTime), CAST(N'2017-12-31 00:00:00.000' AS DateTime), N'SOURCEE')
INSERT [dbo].[tblBudget] ([Ref], [SourceID], [BudgetRevenue], [BudgetHires], [BudgetSold], [BudgetInstructions], [SourceGroup], [MonthFrom], [MonthTo], [Name]) VALUES (7, 7, 566.0000, 23, 12, 44, NULL, CAST(N'2017-12-01 00:00:00.000' AS DateTime), CAST(N'2017-12-31 00:00:00.000' AS DateTime), N'SOURCED')
INSERT [dbo].[tblBudget] ([Ref], [SourceID], [BudgetRevenue], [BudgetHires], [BudgetSold], [BudgetInstructions], [SourceGroup], [MonthFrom], [MonthTo], [Name]) VALUES (8, 8, 668.0000, 3, 44, 23, NULL, CAST(N'2017-12-01 00:00:00.000' AS DateTime), CAST(N'2017-12-31 00:00:00.000' AS DateTime), N'SOURCEC')
SET IDENTITY_INSERT [dbo].[tblBudget] OFF
Second table of cases.
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tblCase](
[PK_RefNo] [int] IDENTITY(1,1) NOT NULL,
[SourceID] [int] NOT NULL,
[DateInstructed] [datetime] NOT NULL,
[DateClosed] [datetime] NULL,
[Insurer_tpi] [varchar](50) NULL,
[HireDailyRate] [money] NULL,
[ActualStartDate] [datetime] NULL,
[ActualFinishDate] [datetime] NULL,
[HireContractRate] [money] NULL,
[DailyRate] [money] NULL,
[AdditionalCosts] [money] NULL,
CONSTRAINT [PK_tblCase] PRIMARY KEY CLUSTERED
(
[PK_RefNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[tblCase] ON
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (1, 1, CAST(N'2017-10-09 00:00:00.000' AS DateTime), CAST(N'2017-12-13 00:00:00.000' AS DateTime), N'avg', 2.0000, CAST(N'2017-11-14 00:00:00.000' AS DateTime), CAST(N'2017-12-19 00:00:00.000' AS DateTime), 2.0000, 1.0000, 3.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (2, 1, CAST(N'2017-01-10 00:00:00.000' AS DateTime), CAST(N'2018-01-16 00:00:00.000' AS DateTime), N'Bull', 4.0000, CAST(N'2017-01-03 00:00:00.000' AS DateTime), NULL, 4.0000, 3.0000, 1.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (3, 3, CAST(N'2017-12-13 00:00:00.000' AS DateTime), CAST(N'2018-01-01 00:00:00.000' AS DateTime), N'bit', 3.0000, CAST(N'2017-12-13 00:00:00.000' AS DateTime), CAST(N'2017-12-27 00:00:00.000' AS DateTime), 5.0000, 3.0000, 1.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (4, 4, CAST(N'2017-12-02 00:00:00.000' AS DateTime), CAST(N'2018-01-01 00:00:00.000' AS DateTime), N'Avast', 5.0000, CAST(N'2017-12-15 00:00:00.000' AS DateTime), CAST(N'2017-12-27 00:00:00.000' AS DateTime), 5.0000, 4.0000, 2.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (5, 5, CAST(N'2017-12-08 00:00:00.000' AS DateTime), NULL, N'Kasp', 6.0000, CAST(N'2017-12-22 00:00:00.000' AS DateTime), CAST(N'2018-01-26 00:00:00.000' AS DateTime), 6.0000, 4.0000, 2.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (6, 1, CAST(N'2017-12-06 00:00:00.000' AS DateTime), CAST(N'2018-01-01 00:00:00.000' AS DateTime), N'avg', 5.0000, CAST(N'2017-10-10 00:00:00.000' AS DateTime), CAST(N'2017-12-27 00:00:00.000' AS DateTime), 6.0000, 4.0000, 2.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (7, 1, CAST(N'2017-09-01 00:00:00.000' AS DateTime), CAST(N'2018-01-01 00:00:00.000' AS DateTime), N'avg', 5.0000, CAST(N'2017-11-01 00:00:00.000' AS DateTime), CAST(N'2017-12-08 00:00:00.000' AS DateTime), 5.0000, 4.0000, 1.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (8, 4, CAST(N'2017-12-05 00:00:00.000' AS DateTime), CAST(N'2018-01-11 00:00:00.000' AS DateTime), N'Avast', 6.0000, CAST(N'2017-11-30 00:00:00.000' AS DateTime), CAST(N'2018-01-03 00:00:00.000' AS DateTime), 4.0000, 3.0000, 1.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (9, 4, CAST(N'2017-12-05 00:00:00.000' AS DateTime), CAST(N'2018-01-10 00:00:00.000' AS DateTime), N'Panda', 6.0000, CAST(N'2017-12-04 00:00:00.000' AS DateTime), CAST(N'2017-12-30 00:00:00.000' AS DateTime), 6.0000, 4.0000, 2.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (10, 5, CAST(N'2017-01-10 00:00:00.000' AS DateTime), CAST(N'2018-01-01 00:00:00.000' AS DateTime), N'Avast', 7.0000, CAST(N'2017-12-13 00:00:00.000' AS DateTime), CAST(N'2018-01-24 00:00:00.000' AS DateTime), 6.0000, 4.0000, 1.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (11, 8, CAST(N'2017-05-17 00:00:00.000' AS DateTime), CAST(N'2018-09-07 00:00:00.000' AS DateTime), N'Bull', 3.0000, CAST(N'2017-12-04 00:00:00.000' AS DateTime), CAST(N'2017-12-26 00:00:00.000' AS DateTime), 5.0000, 3.0000, 2.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (12, 2, CAST(N'2017-01-16 00:00:00.000' AS DateTime), CAST(N'2017-12-20 00:00:00.000' AS DateTime), N'bit', 5.0000, CAST(N'2017-12-16 00:00:00.000' AS DateTime), CAST(N'2017-12-20 00:00:00.000' AS DateTime), 6.0000, 5.0000, 2.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (13, 8, CAST(N'2017-12-05 00:00:00.000' AS DateTime), CAST(N'2017-12-20 00:00:00.000' AS DateTime), N'Avast', 6.0000, CAST(N'2001-03-01 00:00:00.000' AS DateTime), CAST(N'2017-12-27 00:00:00.000' AS DateTime), 6.0000, 1.0000, 2.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (14, 8, CAST(N'2017-12-12 00:00:00.000' AS DateTime), CAST(N'2017-12-19 00:00:00.000' AS DateTime), N'Kasp', 5.0000, CAST(N'2017-11-30 00:00:00.000' AS DateTime), CAST(N'2018-01-02 00:00:00.000' AS DateTime), 6.0000, 3.0000, 1.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (15, 8, CAST(N'2017-12-04 00:00:00.000' AS DateTime), CAST(N'2017-12-28 00:00:00.000' AS DateTime), N'Panda', 6.0000, CAST(N'2017-11-30 00:00:00.000' AS DateTime), CAST(N'2018-01-03 00:00:00.000' AS DateTime), 5.0000, 3.0000, 2.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (16, 2, CAST(N'2017-12-05 00:00:00.000' AS DateTime), CAST(N'2017-12-20 00:00:00.000' AS DateTime), N'Avast', 6.0000, CAST(N'2017-12-01 00:00:00.000' AS DateTime), CAST(N'2017-12-19 00:00:00.000' AS DateTime), 5.0000, 1.0000, 2.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (17, 6, CAST(N'2017-12-05 00:00:00.000' AS DateTime), CAST(N'2018-01-10 00:00:00.000' AS DateTime), N'Avast', 6.0000, CAST(N'2017-11-30 00:00:00.000' AS DateTime), CAST(N'2017-12-30 00:00:00.000' AS DateTime), 5.0000, 1.0000, 3.0000)
INSERT [dbo].[tblCase] ([PK_RefNo], [SourceID], [DateInstructed], [DateClosed], [Insurer_tpi], [HireDailyRate], [ActualStartDate], [ActualFinishDate], [HireContractRate], [DailyRate], [AdditionalCosts]) VALUES (18, 5, CAST(N'2017-12-05 00:00:00.000' AS DateTime), CAST(N'2018-01-10 00:00:00.000' AS DateTime), N'Avast', 6.0000, CAST(N'2017-11-30 00:00:00.000' AS DateTime), CAST(N'2018-01-03 00:00:00.000' AS DateTime), 6.0000, 3.0000, 1.0000)
SET IDENTITY_INSERT [dbo].[tblCase] OFF
If hope you understand the question.
Maybe this
select * from tblbudget
left join
(
select
[SourceID],
hirevalue = sum((datediff(d,
(case when actualstartdate < '2017-12-01' then '2017-12-01'
else actualstartdate
end),
(case when actualfinishdate > '2017-12-31' or actualfinishdate is null then '2017-12-31'
else actualfinishdate
end)
) + 1) * (case when Insurer_tpi = 'avg' then hiredailyrate else dailyrate end) )
from tblcase
where (actualstartdate >= '2017-12-01' and actualstartdate <='2017-12-31')
or
(actualfinishdate >= '2017-12-01' and actualfinishdate <='2017-12-31')
or
(actualstartdate < '2017-12-01' and actualfinishdate > '2017-12-31')
or
(actualstartdate < '2017-12-01' and actualfinishdate is null)
group by sourceid
) cases on cases.sourceid = tblbudget.Sourceid
Ref SourceID BudgetRevenue BudgetHires BudgetSold BudgetInstructions SourceGroup MonthFrom MonthTo Name SourceID hirevalue
----------- ----------- --------------------- ----------- ----------- ------------------ ----------- ----------------------- ----------------------- -------------------------------------------------- ----------- ---------------------
1 1 300.00 12 45 80 NULL 2017-12-01 00:00:00.000 2017-12-31 00:00:00.000 SOURCEA 1 306.00
2 2 400.00 15 50 90 NULL 2017-12-01 00:00:00.000 2017-12-31 00:00:00.000 SOURCEB 2 44.00
3 3 700.00 4 6 50 NULL 2017-12-01 00:00:00.000 2017-12-31 00:00:00.000 SOURCEH 3 45.00
4 4 323.00 6 18 50 NULL 2017-12-01 00:00:00.000 2017-12-31 00:00:00.000 SOURCEG 4 253.00
5 5 567.00 6 45 56 NULL 2017-12-01 00:00:00.000 2017-12-31 00:00:00.000 SOURCEF 5 209.00
6 6 566.00 12 56 67 NULL 2017-12-01 00:00:00.000 2017-12-31 00:00:00.000 SOURCEE 6 30.00
7 7 566.00 23 12 44 NULL 2017-12-01 00:00:00.000 2017-12-31 00:00:00.000 SOURCED NULL NULL
8 8 668.00 3 44 23 NULL 2017-12-01 00:00:00.000 2017-12-31 00:00:00.000 SOURCEC 8 282.00
(8 row(s) affected)

Daily report of sales using Pivot table SQL server with multiple values under each date column

I have to send a weekly report to the Administrator from a website. The weekly report looks something like below image.
ATV (Average Transaction Value) and UPT (Units per transaction)
Table schema and sample data are given below
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Sale](
[Id] [nvarchar](128) NOT NULL,
[UserId] [nvarchar](128) NOT NULL,
[StoreId] [nvarchar](128) NOT NULL,
[SaleAmount] [decimal](18, 2) NOT NULL,
[CreatedDate] [datetime] NOT NULL,
[Note] [nvarchar](max) NULL,
[ATV] [decimal](18, 2) NOT NULL DEFAULT ((0)),
[UPT] [decimal](18, 2) NOT NULL DEFAULT ((0)),
CONSTRAINT [PK_dbo.Sale] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[Store] Script Date: 12-Jun-17 2:20:36 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Store](
[Id] [nvarchar](128) NOT NULL,
[Title] [nvarchar](1000) NOT NULL,
[Address1] [nvarchar](100) NULL,
[Address2] [nvarchar](100) NULL,
[Address3] [nvarchar](100) NULL,
[City] [nvarchar](100) NULL,
[State] [nvarchar](100) NULL,
[Country] [nvarchar](100) NULL,
[ZipCode] [nvarchar](100) NULL,
[Telephone1] [nvarchar](100) NULL,
[Telephone2] [nvarchar](100) NULL,
[Telephone3] [nvarchar](100) NULL,
[Location] [geography] NULL,
[IsActive] [bit] NOT NULL DEFAULT ((0)),
[Rank] [int] NOT NULL DEFAULT ((0)),
CONSTRAINT [PK_dbo.Store] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
INSERT [dbo].[Sale] ([Id], [UserId], [StoreId], [SaleAmount], [CreatedDate], [Note], [ATV], [UPT]) VALUES (N'11', N'9d5626d9-a71e-4116-bae5-4e6d736986c3', N'c71c82aa-2ad0-4599-b6d2-17a21a7b98da', CAST(9000.00 AS Decimal(18, 2)), CAST(N'2017-06-04 10:50:04.997' AS DateTime), N'5th', CAST(16.00 AS Decimal(18, 2)), CAST(27.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Sale] ([Id], [UserId], [StoreId], [SaleAmount], [CreatedDate], [Note], [ATV], [UPT]) VALUES (N'12', N'9d5626d9-a71e-4116-bae5-4e6d736986c3', N'c71c82aa-2ad0-4599-b6d2-17a21a7b98da', CAST(8000.00 AS Decimal(18, 2)), CAST(N'2017-06-05 10:50:04.997' AS DateTime), N'4th', CAST(15.00 AS Decimal(18, 2)), CAST(26.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Sale] ([Id], [UserId], [StoreId], [SaleAmount], [CreatedDate], [Note], [ATV], [UPT]) VALUES (N'13', N'9d5626d9-a71e-4116-bae5-4e6d736986c3', N'c71c82aa-2ad0-4599-b6d2-17a21a7b98da', CAST(7000.00 AS Decimal(18, 2)), CAST(N'2017-06-06 10:50:04.997' AS DateTime), N'3rd', CAST(14.00 AS Decimal(18, 2)), CAST(25.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Sale] ([Id], [UserId], [StoreId], [SaleAmount], [CreatedDate], [Note], [ATV], [UPT]) VALUES (N'14', N'9d5626d9-a71e-4116-bae5-4e6d736986c3', N'c71c82aa-2ad0-4599-b6d2-17a21a7b98da', CAST(6000.00 AS Decimal(18, 2)), CAST(N'2017-06-07 10:50:04.997' AS DateTime), N'second', CAST(13.00 AS Decimal(18, 2)), CAST(24.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Sale] ([Id], [UserId], [StoreId], [SaleAmount], [CreatedDate], [Note], [ATV], [UPT]) VALUES (N'15', N'9d5626d9-a71e-4116-bae5-4e6d736986c3', N'c71c82aa-2ad0-4599-b6d2-17a21a7b98da', CAST(5000.00 AS Decimal(18, 2)), CAST(N'2017-06-08 10:50:04.997' AS DateTime), N'TEST', CAST(12.00 AS Decimal(18, 2)), CAST(23.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Sale] ([Id], [UserId], [StoreId], [SaleAmount], [CreatedDate], [Note], [ATV], [UPT]) VALUES (N'16', N'9d5626d9-a71e-4116-bae5-4e6d736986c3', N'c71c82aa-2ad0-4599-b6d2-17a21a7b98da', CAST(10000.00 AS Decimal(18, 2)), CAST(N'2017-06-09 10:50:04.997' AS DateTime), N'6th', CAST(17.00 AS Decimal(18, 2)), CAST(28.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Sale] ([Id], [UserId], [StoreId], [SaleAmount], [CreatedDate], [Note], [ATV], [UPT]) VALUES (N'17', N'9d5626d9-a71e-4116-bae5-4e6d736986c3', N'c71c82aa-2ad0-4599-b6d2-17a21a7b98da', CAST(888.00 AS Decimal(18, 2)), CAST(N'2017-06-10 10:43:49.693' AS DateTime), N'test test2', CAST(12.00 AS Decimal(18, 2)), CAST(13.00 AS Decimal(18, 2)))
GO
INSERT [dbo].[Store] ([Id], [Title], [Address1], [Address2], [Address3], [City], [State], [Country], [ZipCode], [Telephone1], [Telephone2], [Telephone3], [Location], [IsActive], [Rank]) VALUES (N'67586972-6694-444a-9426-a0e6e4066015', N'store 3', N'1', N'Unnamed Road', NULL, N'Richmond', N'England', N'United Kingdom', N'DL11 6RR', NULL, NULL, NULL, NULL, 1, 3)
GO
INSERT [dbo].[Store] ([Id], [Title], [Address1], [Address2], [Address3], [City], [State], [Country], [ZipCode], [Telephone1], [Telephone2], [Telephone3], [Location], [IsActive], [Rank]) VALUES (N'68ece12f-c3e7-4705-88eb-2a0da2d7c1cc', N'Test Product', N'tesadf', N'323', N'asdf', N'sdf23', N'234', N'United Kingdom', N'234', NULL, NULL, NULL, NULL, 1, 4)
GO
INSERT [dbo].[Store] ([Id], [Title], [Address1], [Address2], [Address3], [City], [State], [Country], [ZipCode], [Telephone1], [Telephone2], [Telephone3], [Location], [IsActive], [Rank]) VALUES (N'c71c82aa-2ad0-4599-b6d2-17a21a7b98da', N'Store 1', N'Greenhillstairs', NULL, NULL, N'Moffat', N'Scotland', N'United Kingdom', N'DG10 9SP', NULL, NULL, NULL, 0xE6100000010C5278753348B04B406FEE5465841C0CC0, 1, 1)
GO
INSERT [dbo].[Store] ([Id], [Title], [Address1], [Address2], [Address3], [City], [State], [Country], [ZipCode], [Telephone1], [Telephone2], [Telephone3], [Location], [IsActive], [Rank]) VALUES (N'f26f67f1-e8f7-44a4-aaac-e861d18d54f3', N'Store 2', N'Lythe Fell Road', NULL, NULL, NULL, N'England', N'United Kingdom', NULL, NULL, NULL, NULL, 0xE6100000010C640D72721A054B40729472ADACD303C0, 1, 2)
GO
Below pivot query
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
declare #fromDate AS NVARCHAR(MAX)
set #fromDate=CAST('2017-06-04 10:50:04.997' AS DATE)
SELECT CAST(CreatedDate AS DATE) [Date], sum(saleamount) [SaleTotal], ATV,UPT
INTO #PivotSalesData2
FROM sale
where createddate>='2017-06-04 10:50:04.997'
GROUP BY CAST(Createddate AS DATE),storeid,ATV,UPT
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME([Date])
FROM #PivotSalesData2
print #columnName
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT * from (SELECT (select Title from store where id=storeid ) storeid, CAST(CreatedDate AS DATE) [Date],
sum(atv) [atv]
FROM Sale
where createddate>=#fromDate
GROUP BY CAST(CreatedDate AS DATE),storeid,atv) AS DailyData
PIVOT( sum([atv])
FOR [Date] IN (' + #ColumnName + ')) AS PVTTable'
print #DynamicPivotQuery
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery , N'#fromDate nvarchar(max)', #fromDate = #fromDate
Generate following output
enter image description here
But I need ATV and UPT column values under each date column
This I have tested with your sample data.
Let me know the final output that you are looking for and you output and input should in tandem.
SET #DynamicPivotQuery =
N'
SELECT * from
(select UserId,sum( [ATV])atv
,DATENAME(dw,CreatedDate) createddate
FROM #Sale
group by userid,createddate
) AS DailyData
PIVOT( sum(atv)
FOR createddate IN ('+#ColumnName+')
) AS PVTTable
union ALL
SELECT * from
(select UserId,sum( [UPT])[UPT]
,DATENAME(dw,CreatedDate) createddate
FROM #Sale
group by userid,createddate
) AS DailyData
PIVOT( sum(upt)
FOR createddate IN ('+#ColumnName+')
) AS PVTTable
'
print #DynamicPivotQuery
exec (#DynamicPivotQuery)

Resources