I have a SQL view on my database to print a report on C# and Itext7 using Lot and PartNumberId to find the results
DECLARE @LotId int = '1'
DECLARE @PartNumerId int = '100'
SELECT * FROM vw_report_diarydefects WHERE LotId = @LotId AND PartNumerId = @PartNumerId
| Lot | PartNumberId | PartNumber | DefectId | Defect | Qty | SortingDate |
|---|---|---|---|---|---|---|
| 1 | 100 | WD40 | 1 | Broken | 9 | 2019-10-01 10:31:02.000 |
| 1 | 100 | WD40 | 2 | Paint Scratch | 10 | 2019-10-02 10:31:02.000 |
| 1 | 100 | WD40 | 3 | Swollen | 8 | 2019-10-02 10:31:02.000 |
| 1 | 100 | WD40 | 2 | Paint Scratch | 10 | 2019-10-03 10:31:02.000 |
| 1 | 100 | WD40 | 4 | Bent | 5 | 2019-10-04 10:31:02.000 |
What i want to do is put the SortingDate as columns and add the quantity on them like this:
| Defect | 2019-10-01 10:31:02.000 | 2019-10-02 10:31:02.000 | 2019-10-03 10:31:02.000 | 2019-10-04 10:31:02.000 |
|---|---|---|---|---|
| Broken | 9 | 0 | 0 | 0 |
| Paint Scratch | 0 | 10 | 10 | 0 |
| Swollen | 0 | 8 | 0 | 0 |
| Bent | 0 | 0 | 0 | 5 |
I used pivot (my 1st time using it) and i have use this:
DECLARE @StuffColumn varchar(max)
DECLARE @sql varchar(max)
DECLARE @LotId int = '1'
DECLARE @PartNumerId int = '100'
SELECT @StuffColumn = STUFF((SELECT distinct ','+QUOTENAME(SortingDate)
FROM vw_report_diarydefects
WHERE LotId = @LotId AND PartNumerId = @PartNumerId
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @SQL = ' select Defect, '+ @StuffColumn +'
from
(
select SortingDate,Defect,Qty
from vw_report_diarydefects
where LotId = ''' + CONVERT(NVARCHAR(50), @LotId, 121)+ ''' and PartNumerId = ''' + CONVERT(NVARCHAR(50), @PartNumerId, 121)+ '''
)x
pivot
(
Sum(Qty)
for SortingDate in( '+@StuffColumn+' )
)p'
EXEC(@SQL)
Getting just this:
| Defect | Oct 1 2019 10:31AM | Oct 2 2019 10:31AM | Oct 3 2019 10:31AM | Oct 4 2019 10:31AM |
|---|---|---|---|---|
| Broken | NULL | NULL | NULL | NULL |
| Paint Scratch | NULL | NULL | NULL | NULL |
| Swollen | NULL | NULL | NULL | NULL |
| Bent | NULL | NULL | NULL | NULL |
Is there a way to fill the Date Columns with the quantity data? Is my first time using Pivot, i am reading about that instruction but i still have some doubts.