I am working in a restaurant project. I have 4 table for sale module.
order master.
order details.
itemEntry
waiter_info
They require a report which will show each item sale quantity for each waiter.
MENU_NAME MENU_ID PRICE Total Foisal Kamal Sajib
Naan 2 10.00 8 6 2 0
Parata 1 10.00 10 6 4 0
Vaji 3 30.00 15 8 6 1
My query is below:
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(Name)
FROM (SELECT DISTINCT Name FROM Waiter_Info) AS Waiter
print #ColumnName
SET #DynamicPivotQuery = N'
SELECT * from vw_ItemWiseSale
pivot
(
sum(QUANTITY) for WAITER in ('+ #ColumnName +')) as pvt'
EXEC sp_executesql #DynamicPivotQuery
My output is:
MENU_NAME MENU_ID PRICE Total Foisal Kamal Sajib
Naan 2 10.00 20 NULL 2 NULL
Naan 2 10.00 60 6 NULL NULL
Parata 1 10.00 40 NULL 4 NULL
Parata 1 10.00 60 6 NULL NULL
Vaji 3 30.00 30 NULL NULL 1
Vaji 3 30.00 180 NULL 6 NULL
Vaji 3 30.00 240 8 NULL NULL
Please help me to get expected output item wise which mentioned in 3 line.(i,e each row for every item)
Related
I understand how to use PIVOT to rotate rows into columns but I have a unique scenario where rows also have to be grouped. The source data is from a NoSQL database schema (un-relational). Here is an example of the source data:
ID case_id field_id sequence_number textvalue
1 12897 25 100 AAAAA
2 12897 50 100 BBBBB
3 12897 75 100 CCCCC
4 13587 25 200 DDDDD
5 13587 50 200 EEEEE
6 13587 75 200 FFFFF
7 13587 100 200 GGGGG
The result I need is:
case_id value_field_id_25 value_field_id_50 value_field_id_75 value_field_id_100
12897 AAAAA BBBBB CCCCC
13587 DDDDD EEEEE FFFFF GGGGG
So, what I need is a row of related records grouped by sequence_number. The number of rows with the same sequence_number is dynamic (it varies).
Any ideas?
Declare #SQL varchar(max) = Stuff((Select ',' + QuoteName('value_field_id_'+cast(field_id as varchar(25)))
From (Select Distinct Top 100 Percent field_id
From YourTable
Order by 1) A
For XML Path('')),1,1,'')
Select #SQL = '
Select [case_id],' + #SQL + '
From (
Select sequence_number
,case_id
,ColName = ''value_field_id_''+cast(field_id as varchar(25))
,Value = textvalue
From YourTable A
) A
Pivot (max([Value]) For [ColName] in (' + #SQL + ') ) p'
Exec(#SQL);
Returns
I have a table with thousands of records and sample is given below.
There is only [DateOfBirth] field in the table and I need to calculate age range with total count :
ID Name DateOfBirth
1 John 1980-11-20 00:00:00.000
2 Denial 1940-04-10 00:00:00.000
3 Binney 1995-12-25 00:00:00.000
4 Sara 1960-11-20 00:00:00.000
5 Poma 1980-11-20 00:00:00.000
6 Cameroon 1980-11-20 00:00:00.000
.....
.....
I need to write the SQL Query to display output 10 years age range to fit it in the bar chart.
AgeRange Count
1-10 100
11-20 200
21-30 400
31-40 0
41-50 800
51-60 700
61-70 200
.....
.....
and so on if the age person is present in the table.
Please try the below query
select
cast( 1 + DateDiff(YY,DATEADD(YY,-1,DateOfBirth),getdate())/10 *10 as varchar)+ '-'+ cast(10+ DateDiff(YY,DATEADD(YY,-1,DateOfBirth),getdate())/10 *10 as varchar) as AgeRange
,
count(1) as count
from tbl
group by
DateDiff(YY,DATEADD(YY,-1,DateOfBirth),getdate())/10
Demo link here
update: based on your custom range, you should use this query
select
cast(case when
DateDiff(YY,DATEADD(YY,-1,DateOfBirth),getdate())/10 =0
then 0
else
1 end+ DateDiff(YY,DATEADD(YY,-1,DateOfBirth),getdate())/10 *10 as varchar)+ '-'+ cast(10+ DateDiff(YY,DATEADD(YY,-1,DateOfBirth),getdate())/10 *10 as varchar) as AgeRange
,
count(1) as count
from tbl
group by
DateDiff(YY,DATEADD(YY,-1,DateOfBirth),getdate())/10
this seems to work for me
SELECT count(*) as [count]
, cast(datediff(YYYY, value, getdate())/10 * 10 as varchar(10)) + ' - ' +
cast(datediff(YYYY, value, getdate())/10 * 10 + 9 as varchar(10)) as range
FROM [docSVdate]
group by datediff(YYYY, value, getdate())/10
order by datediff(YYYY, value, getdate())/10 desc
this start with 0 then just adds 9
you need to be consistent as 0 - 10 is a range of 11
if you need to start on 1 then I think you need also change the group by
Using SQL Server 2012.
I have the following table. The Style and colour are passed as a parameter:
Style Colour Size Whse Stock Sales 4WeekSales ATP
ABC123 AS12 10 London 2 3 6 7
ABC123 AS12 12 London 4 6 8 10
ABC123 AS12 14 New York 6 8 9 12
ABC123 AS12 10 New York 7 5 7 5
But need the data to look like this with the sizes along the top:
Whse 10 12 14
Lon
Stock 2 4 6
Sales 3 6 8
4WeekSales 6 8 9
ATP 7 10 12
New York
Stock 7 6
Sales 5 8
4WeekSales 7 9
ATP 5 12
Points to note - the size field needs to be dynamic - sometimes it can be 6 /8/10/12, sometimes it can be XS/S/M/L etc
Also their are more than two whse's - this is just an example.
I did make a start in T-SQL:
use SafetyStock
go
DECLARE #columns NVARCHAR(MAX), #sql NVARCHAR(MAX);
SET #columns = N'';
SELECT #columns += N', p.' + QUOTENAME(Size)
FROM (SELECT p.Size FROM dbo.vw_optimums AS p
GROUP BY p.Size) AS x;
SET #sql = N'
SELECT SKU, Style,' + STUFF(#columns, 1, 2, '') + '
FROM
(
SELECT SKU, Style, p.Size, p.SAFETYSTOCK
FROM dbo.vw_optimums AS p
) AS j
PIVOT
(
SUM(SAFETYSTOCK) FOR Size IN ('
+ STUFF(REPLACE(#columns, ', p.[', ',['), 1, 1, '')
+ ')
) AS p;';
PRINT #sql;
EXEC sp_executesql #sql;
However, this works but only pivots on the stock - how do I also pivot by Sales\4WeekSales\ATP and also groupb by the whse?
Thank you in advance.
This is my latest code. If I take the SEQNO out it works, but I need this so the sizes appear along the top correctly e.g. S / M / L / XL / XXL etc or 6/ 8 / 10 / 12
DECLARE #SizeColums VARCHAR(MAX)
DECLARE #Seq Integer
SELECT
#SizeColums = COALESCE(#SizeColums + ',','') + QUOTENAME([Size]),
#Seq = SEQNO
FROM vw_optimums1
GROUP BY [Size],[SEQNO]
ORDER BY [SEQNO]
DECLARE #Sql NVARCHAR(MAX) = N'
SELECT Whse,
[Types],' +
#SizeColums + '
FROM (SELECT * FROM vw_optimums1) t
UNPIVOT (
[Type]
FOR [Types] IN ([Stock],[LWSALES],[L4WSALES],[ATP]) ) up
PIVOT (
MAX([Type])
FOR [Size] IN (' + #SizeColums + ')
) p
'
EXEC sp_executesql #sql;
About the closest I can get you is this.
DECLARE #SizeColums VARCHAR(MAX)
SELECT #SizeColums = COALESCE(#SizeColums + ',','') + QUOTENAME([Size])
FROM vw_optimums
GROUP BY [Size]
DECLARE #Sql NVARCHAR(MAX) = N'
SELECT Whse,
[Types],' +
#SizeColums + '
FROM (SELECT * FROM vw_optimums
) t
UNPIVOT (
[Type]
FOR [Types] IN ([Stock],[Sales],[4WeekSales],[ATP]) ) up
PIVOT (
MAX([Type])
FOR [Size] IN (' + #SizeColums + ')
) p
'
This actually uses UNPIVOT first to get the breakdown by size, then pivots based on size.
You'll get a result like this based on the sample data.
Whse Types 10 12 14
-------- -------------- ----------- ----------- -----------
London 4WeekSales 6 8
London ATP 7 10
London Sales 3 6
London Stock 2 4
New York 4WeekSales 7 9
New York ATP 5 12
New York Sales 5 8
New York Stock 7 6
I have a PIVOT situation.
Source table columns:
Title Description Datetime RecordsCount
A California 2015-07-08 10:44:39.040 5
A California 2015-07-08 12:44:39.040 6
A California 2015-05-08 15:44:39.040 3
B Florida 2015-07-08 16:44:39.040 2
B Florida 2015-05-08 19:44:39.040 4
Now I need this pivoted as
2015-07-08 2015-05-08
Title Description
A California 11 3
B Florida 2 4
if we have two record counts on same dates (no matter of time) then sum them, else display in different column.
Trying to write something like this, but it throws errors.
Select * from #DataQualTest
PIVOT (SUM(RecordCount) FOR DateTime IN (Select Datetime from #DataQualTest) )
AS Pivot_Table
Please help me out with this.
Thanks
Not exactly the word for word solution but this should give you a direction.
create table #tmp
(
country varchar(max)
, date1 datetime
, record int
)
insert into #tmp values ('California', '2010-01-01', 2)
insert into #tmp values ('California', '2010-01-01', 5)
insert into #tmp values ('California', '2012-01-01', 1)
insert into #tmp values ('Florida', '2010-01-01', 3)
insert into #tmp values ('Florida', '2010-01-01', 5)
select * from #tmp
pivot (sum(record) for date1 in ([2010-01-01], [2012-01-01])) as avg
output
country 2010-01-01 2012-01-01
California 7 1
Florida 8 NULL
If you want to be more flexible, you need some pre-processing to get from full timestamps to days (in order for later on the PIVOT's grouping to actually have the anticipated effect):
CREATE VIEW DataQualTestView AS
SELECT
title
, description
, DATEFROMPARTS (DATEPART(yyyy, date_time),
DATEPART(mm, date_time),
DATEPART(dd, date_time)) AS day_from_date_time
, recordsCount
FROM DataQualTest
;
From there you could continue:
DECLARE #query AS NVARCHAR(MAX)
DECLARE #columns AS NVARCHAR(MAX)
SELECT #columns = ISNULL(#columns + ',' , '')
+ QUOTENAME(day_from_date_time)
FROM (SELECT DISTINCT
day_from_date_time
FROM DataQualTestView) AS TheDays
SET #query =
N'SELECT
title
, description
, ' + #columns + '
FROM DataQualTestView
PIVOT(SUM(recordsCount)
FOR day_from_date_time IN (' + #columns + ')) AS Pivoted'
EXEC SP_EXECUTESQL #query
GO
... and would get:
| title | description | 2015-05-08 | 2015-07-08 |
|-------|-------------|------------|------------|
| A | California | 3 | 11 |
| B | Florida | 4 | 2 |
See it in action: SQL Fiddle.
Please comment, if and as this requires adjustment / further detail.
We have a table like below
.
.
.
.
.
ID WOID InfoCode PersonID PersonSource FieldID FieldName FieldValue
--------------------------------------------------------------------------------------
1 2 AGMDDFR 7 CSS2C 1 Email sg
2 2 AGMDDFR 7 CSS2C 2 Phone 245345
3 2 AGMDDFR 7 CSS2C 3 FAX 345345
4 2 AGMDDFR 7 CSS2C 4 ArticleNumber 345
5 2 AGMDDFR 7 CSS2C 6 Description etete
6 2 ABC 7 CSS2C 12 Enter Email
7 2 AGMDDFR 8 CSS2C 1 Email tet#gmi.com
8 2 AGMDDFR 8 CSS2C 2 Phone 9988776655
9 2 AGMDDFR 8 CSS2C 3 FAX 898383838
10 2 AGMDDFR 8 CSS2C 4 Article Number 777777
11 2 AGMDDFR 8 CSS2C 6 Description asdff
we want output like below based on 'Info Code' we need to extract tables like below.
---1stTable(AGMDDFR)----
WOID PersonID PersonSource Email Phone Fax ArticleNumber Description
-----------------------------------------------------------------------------------------
2 7 CSS2C sg 245345 345345 345 etete
2 8 CSS2C tet#gmi.com 9988776655 898383838 777777 asdff
--2ndTable(ABC)
WOID PersonID PersonSource Enter Email
2 7 CSS2C ssss
Please help me how to solve this issue..
Since you need to return different columns for each InfoCode value, you'll need to look at using dynamic SQL to get the result. This will create a SQL string that contains the list of columns for each parameter. You'll then execute the SQL string to get the final result.
The basic syntax will be:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX),
#InfoCode varchar(10)
DECLARE #ParmDefinition NVARCHAR(500)
set #InfoCode = 'AGMDDFR'
SET #ParmDefinition = '#InfoCode varchar(10)'
select #cols = STUFF((SELECT ',' + QUOTENAME(FieldName)
from yourtable
where InfoCode = #InfoCode
group by FieldName, FieldID
order by FieldId
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT WOID, PersonID, PersonSource, ' + #cols + '
from
(
select WOID, PersonID, PersonSource,
FieldName, FieldValue
from yourtable
where InfoCode = #InfoCode
) x
pivot
(
max(FieldValue)
for FieldName in (' + #cols + ')
) p '
EXEC sp_executesql #query, #ParmDefinition, #InfoCode = #InfoCode;
See SQL Fiddle with Demo