Draw a dynamic table in SQL - sql

Good morning, I'm trying to draw a dynamic table with some data, this query, draw a table that has a day, his week, and some data that I want to calculate dynamically.
This is my query
use Alfri
;with monthDates
as
(
select DATEADD(month, 0, CONVERT(DATE,'2013-09-09',102)) as d
,DATEPART(week, DATEADD(month, datediff(month, 0, '2013-09-09'),0)) as w,
(
SELECT SUM(
CASE WHEN arrive_yard IS NOT NULL THEN
DATEDIFF(mi, Solicitado, Libre)-DATEDIFF(mi, arrive_yard, leave_yard)
ELSE
DATEDIFF(mi, Solicitado, Libre)
END
) as Tiempo
FROM MovimientoHoras
WHERE CONVERT(DATE, Solicitado, 102) = '2013-10-11'
) as info
union all
select DATEADD(day, 1, d)
,DATEPART(week, DATEADD(day, 1, d))
, info
from monthDates
where d < DATEADD(month, datediff(month, 0, '2013-10-09')+1,-1)
)
SELECT * FROM monthDates
This query draw me a table like this.
d |w |info |
2013-09-09 | 36 | 2780|
2013-09-10 | 37 | 2780|
2013-09-11 | 37 | 2780|
2013-09-12 | 37 | 2780|
2013-09-13 | 37 | 2780|
2013-09-14 | 37 | 2780|
2013-09-15 | 37 | 2780|
2013-09-16 | 37 | 2780|
But the info's column isn't calculling dynamically and this is my dilenma.
The point is that column d is calculated dynamically and that's the value that I want to use in info's column query, something like this WHERE CONVERT(DATE, Solicitado, 102) = d) as info instead of WHERE CONVERT(DATE, Solicitado, 102) = '2013-10-11') as info where D is the date changing in every row, the way that I'm trying it just giving me same data of '2013-10-11'
Something like a While to change a day in that subquery
Thanks

The basic approach is to separate the part that generates dates from the part that calculates the info for that date:
;with monthDates as (
select
cast('20130909' as date) as d,
datepart(week, dateadd(month, datediff(month, 0, '2013-09-09'), 0)) as w
union all
select
dateadd(day, 1, d),
datepart(week, dateadd(day, 1, d))
from
monthDates
where
d < dateadd(month, datediff(month, 0, '2013-10-09') + 1, -1)
)
select
m.d,
m.w,
sum(
datediff(mi, Solicitado, Libre)
- case when arrive_yard is not null then
datediff(mi, arrive_yard, leave_yard)
else 0 end
) info
from
monthDates m
left outer join
MovimientoHoras h
on cast(Solicitado as date) = m.d
group by
m.d,
m.w
Example SQLFiddle

Related

Unpivot subquery

i need to transform this query result into rows instead of columns. Using Unpivot is possible, but I was not able to do this activity
see the code:
SELECT
cast(IIF(DATEPART(HOUR, [DATA]) <= 4, DATEADD(DAY, -1, [DATA]), [DATA]) as date) as Data,
IIF(DATEPART(HOUR, [DATA]) <= 4, DATEADD(DAY, -1, [DATA]), [DATA]) AS DataHora,
SUM([FraturaContusao]) AS 'FraturaContusao',
SUM([Salpingite]) AS 'Salpingite'
FROM
(
SELECT
[DATA], ROMANEIO,
IIF(( bAbaco.FRATURA_CONTUSAO - COALESCE(LAG(bAbaco.FRATURA_CONTUSAO) OVER (ORDER BY bAbaco.ID), 0)) > 0 , ( bAbaco.FRATURA_CONTUSAO - COALESCE(LAG(bAbaco.FRATURA_CONTUSAO) OVER ( ORDER BY bAbaco.ID), 0)), 0) AS 'FraturaContusao',
IIF(( bAbaco.Salpingite - COALESCE(LAG(bAbaco.Salpingite) OVER (ORDER BY bAbaco.ID), 0)) > 0 , ( bAbaco.Salpingite - COALESCE(LAG(bAbaco.Salpingite) OVER ( ORDER BY bAbaco.ID), 0)), 0) AS 'Salpingite'
FROM
ContProdUIA.ABACO_DIGITAL_L2 bAbaco
) as x
WHERE
CONVERT(varchar, x.[DATA], 23) >= DATEADD(DAY, -16, GETDATE())
GROUP BY
IIF(DATEPART(HOUR, [DATA]) <= 4, DATEADD(DAY, -1, [DATA]), [DATA])
this is the result of the query:
I need the columns 'FraturaContusao' and 'Salpingite' to be transformed with unpviot
something like:
Data| DataHora | Tipo| Qty
2020-06-23 | 2020-06-23 15:54 | FraturaContusao| 15
2020-06-23 | 2020-06-23 15:54 | Salpingite | 20
Perhaps the easiest is to use a CROSS APPLY
Example
Select A.Data
,A.DataHora
,B.Tipo
,B.Qty
From (
-- your orignal query here --
) A
Cross Apply ( values ('FraturaContusao',FraturaContusao)
,('Salpingite' ,Salpingite)
) B(Tipo,Qty)

Multiple counts and merge columns

I current have a query that grabs the number of parts made per hour between two dates:
DECLARE #StartDate datetime
DECLARE #EndDate datetime
SET #StartDate = '10/10/2018'
SET #EndDate = '11/11/2018'
SELECT
CONVERT(VARCHAR(10), CAST(presstimes AS DATE), 111) AS ForDate,
DATEPART(HOUR, presstimes) AS OnHour,
COUNT(*) AS Totals
FROM
partmasterlist
WHERE
((presstimes >= #StartDate AND presstimes < dateAdd(d, 1, #EndDate))
AND (((presstimes IS NOT NULL))))
GROUP BY
CONVERT(VARCHAR(10), CAST(presstimes AS DATE), 111),
DATEPART(HOUR, presstimes)
ORDER BY
CONVERT(VARCHAR(10), CAST(presstimes AS DATE), 111) ASC;
Output:
Date Hour QTY
---------------------
2018/11/06 11 16
2018/11/06 12 20
2018/11/06 13 29
2018/11/06 14 26
Now I need to add another qty column to count where "trimmingtimes" is set.
I can't figure out how to full join the date and hour columns (e.g. presstimes might have 20qty for Hour 2, but trimmingtimes is NULL for Hour 2);
Input:
ID presstimes trimmingtimes
-----------------------------------------------------------------
1 2018-10-10 01:15:23.000 2018-10-10 01:15:23.000
2 2018-10-10 01:15:23.000 NULL
3 2018-10-10 02:15:23.000 NULL
4 NULL 2018-10-10 03:15:23.000
Output:
Date hour Press QTY T QTY
------------------------------------
10/10/18 1 2 1
10/10/18 2 1 0
10/10/18 3 0 1
I suspect you want something like this:
select convert(date, v.dt) as date,
datepart(hour, v.dt) as hour,
sum(ispress) as num_press,
sum(istrim) as num_trim
from partmasterlist pml cross apply
(values (pml.presstime, 1, 0), (pml.trimmingtime, 0, 1)
) v(dt, ispress, istrim)
group by convert(date, v.dt), datepart(hour, v.dt)
order by convert(date, v.dt), datepart(hour, v.dt);
You can add a where clause for a particular range.

Pivoting for DATEPART(wk, date)

I have a table like this,
mytable
date | value
2018.09.12 | 1
2018.09.11 | 2
2018.09.10 | 3
I need a query to return sum(value) for the last six weeks. Exactly like this.
week# | value
37 | 6
36 | 0
35 | 0
34 | 8
33 | 9
32 | 10
31 | 11
I have a query to return sumvalue for each week.
SELECT Sum(Value) AS Sumvalue, DATEPART(wk, date) AS [weekNo]
FROM mytable
WHERE Date BETWEEN DATEADD(DAY, -42, GETDATE()) AND GETDATE()
GROUP BY DATEPART(wk, date)
But this can't handle zero values for a week.
How can write a pivoted query to obtain the format?
My try;
SELECT *
FROM (
SELECT Value, DATEPART(wk, date) AS [weekNo]
FROM mytable
WHERE Date BETWEEN DATEADD(DAY, -42, GETDATE()) AND GETDATE()
) As sourcetable
PIVOT
(
Sum(Value) for DATEPART(wk, date) IN (SELECT date FROM mytable where date between
DATEADD(DAY, -42, GETDATE()) and GETDATE())
) AS pivotable
I am getting the syntax error near for keyword. How can I put the six weeks in pivot statemet
Found a partial solution!
SELECT *
FROM (
SELECT Value, DATEPART(wk, date) AS [weekNo]
FROM mytable
WHERE Date BETWEEN DATEADD(DAY, -42, GETDATE()) AND GETDATE()
) As sourcetable
PIVOT
(
Sum(Value) for [week] IN ([1], [2], [3], ... ,[54])
) AS pivotable
It is partial since it is kind of hardcoding the for statement and cannot control the unnecessary weeks in the query.

Iscala Sales Statistics/Month

I am trying to get statistics on monthly sales in iScala ERP. iScala reporting system reports this values.
My Sql query returns
3 058 023 2017-01-01
2 237 651 2017-02-01
4 700 720 2017-03-01
2 268 501 2017-04-01
3 183 576 2017-05-01
3 238 173 2017-06-01
1 949 041 2017-07-01
3 077 111 2017-08-01
My Query, Selecting from invoices SL03 applying Order OR20 to subtract Freight Amount. After that i Union in SL29 Invoice Consolidation History using cross apply to subtract Freight and SaleTax.
BEGIN
SELECT
SUM(cast(replace(isnull(b,0),',','.') as decimal(10,0))) Total,
cast(cast(DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0) as date) as varchar(50)) date
FROM (
SELECT
SUM(SL03100-aa.f) b ,
cast(cast(DATEADD(MONTH, DATEDIFF(MONTH, 0, SL03004), 0) as date) as varchar(50)) d
FROM SL030100
CROSS apply (
SELECT top 1 OR20044 f
FROM OR200100
WHERE SL030100.SL03036 = OR200100.OR20001
) aa
WHERE SL03004 BETWEEN '2017-01-01' AND DATEADD(d, 1,getdate())
group by cast(cast(DATEADD(MONTH, DATEDIFF(MONTH, 0, SL03004), 0) as date) as varchar(50))
UNION
SELECT
SUM((SL29007-SL29009-ba.f)) b,
cast(cast(DATEADD(MONTH, DATEDIFF(MONTH, 0, SL29006), 0) as date) as varchar(50)) d
FROM SL290100
CROSS apply (
SELECT top 1 OR20044 f
FROM OR200100
WHERE SL290100.SL29028 = OR200100.OR20001
) ba
WHERE SL29006 BETWEEN '2017-01-01' AND DATEADD(d, 1,getdate())
group by cast(cast(DATEADD(MONTH, DATEDIFF(MONTH, 0, SL29006), 0) as date) as varchar(50))
) AS tbl
group by cast(cast(DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0) as date) as varchar(50))
order by cast(cast(DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0) as date) as varchar(50))
END
I don't know if this is the best way to do it or what fields are missing. I feel that the difference between the internal report and my SQL result is small but noticeable for the customer.
I hope you can point me in right direction or to some resources that can help.
Best regards
MK

SQL Join Multiple Subqueries - Count Open / Closed by Date

I'm trying to count all open tickets / closed tickets groups by date. Some dates will have 0 values for both but I'd still like to show the date. I feel like I'm close but can't seem to get the grouping correct, it's just giving a total.
DECLARE #DateFrom AS DATE = '11/16/2016'
DECLARE #DateTo AS DATE = GETDATE()
WITH DateRanges AS
(SELECT #DateFrom AS 'DateValue'
UNION ALL
SELECT DATEADD(DAY, 1, DateValue)
FROM DateRanges
WHERE DateValue < #DateTo)
SELECT CONVERT(varchar(10),DateValue, 101) AS "DateVal",
(SELECT
COUNT(OPENDATE)
FROM DateRanges AS a
LEFT OUTER JOIN MAINTABLE
ON a.DateValue = convert(varchar(10), DATEADD(hh, DATEDIFF(HH, GetUTCDATE(), GETDATE()), OPENDATE), 101)
) AS opn,
(SELECT
COUNT(CLOSEDDATE)
FROM DateRanges AS b
LEFT OUTER JOIN MAINTABLE
ON b.DateValue = convert(varchar(10), DATEADD(hh, DATEDIFF(HH, GetUTCDATE(), GETDATE()), CLOSEDDATE), 101)
) AS cls
FROM DateRanges
GROUP BY CONVERT(varchar(10),DateValue, 101)
This produces the following:
DateVal | opn | cls
11/16/2016 | 3 | 3
11/17/2016 | 3 | 3
11/18/2016 | 3 | 3
MainTable
ID | OPENDATE | CLOSEDDATE
123 | 11/16/2016 | 11/16/2016
124 | 11/16/2016 | 11/18/2016
125 | 11/18/2016 | 11/18/2016
Expected Output
DateVal | opn | cls
11/16/2016 | 2 | 1
11/17/2016 | 0 | 0
11/18/2016 | 1 | 2
Thank you for your help
You can use your approach, but you need correlated subqueries, instead of totals:
WITH DateRanges AS (
SELECT #DateFrom AS 'DateValue'
UNION ALL
SELECT DATEADD(DAY, 1, DateValue)
FROM DateRanges
WHERE DateValue < #DateTo
)
SELECT CONVERT(varchar(10), DateValue, 101) AS "DateVal",
(SELECT COUNT(mt.REQDATE)
FROM MAINTABLE mt
WHERE dr.DateValue = convert(varchar(10), DATEADD(hour, DATEDIFF(hour, GetUTCDATE(), GETDATE()), mt.OPENDATE), 101)
) AS opn,
(SELECT COUNT(CLSDDATE)
FROM MAINTABLE mt
WHERE dr.DateValue = convert(varchar(10), DATEADD(hh, DATEDIFF(hour, GetUTCDATE(), GETDATE()), mt.CLOSEDDATE), 101)
) AS cls
FROM DateRanges dr;
Also note that you should not need an aggregation in the outer query.