SQL MAX problems in query - sql

Can anyone tell me why this isn't working? It's giving me ALL the visit dates and I'm just looking for the most recent visit date:
SELECT ID , MAX(CAST((CAST(VISITMO AS nvarchar(2)) + '/' +
CAST(VISITDAY AS nvarchar(2)) + '/' +
CAST(VISITYR AS nvarchar(4))) AS date)
) AS LastVisitDATE
FROM [VisitTable]
WHERE ID IN (SELECT ID FROM Table2 WHERE other criteria is met)
GROUP BY ID, VISITYR, VISITMO, VISITDAY
I kept adding to the GROUP BY statement because of the errors I got

SELECT ID , MAX(CAST((CAST(VISITMO AS nvarchar(2)) + '/' +
CAST(VISITDAY AS nvarchar(2)) + '/' +
CAST(VISITYR AS nvarchar(4))) AS date)
) AS LastVisitDATE
FROM [VisitTable]
GROUP BY ID

Related

SQL order by creation time ASC

I have this query:
SELECT
p.[TerminalId],
Keys = JSON_QUERY('[' + string_agg(json_query('{"Point":"' + p.Location.STAsText() + '","CreatedDateTime":"' + cast(p.CreatedDateTime as nvarchar(20)) + '"}'),',') + ']')
FROM
(SELECT
geography::STGeomFromText(Location.STAsText(), 4326) as Location,
[CreatedDateTime],
[TerminalId],
ROW_NUMBER() OVER (ORDER BY [CreatedDateTime] ASC) AS RowNum
FROM
[Magicar_Route].[dbo].[PacketLocations]) AS p
GROUP BY
p.[TerminalId]
I want p.Location sorted by CreatedDateTime asc in Keys JSON column but after query Location not sorted ASC?
How could I sort my location according CreatedDateTime ASC?
I changed my query to this:
WITH NewScores AS
(
SELECT
geography::STGeomFromText(Location.STAsText(), 4326) AS Location,
[CreatedDateTime],
[TerminalId]
FROM
[Magicar_Route].[dbo].[PacketLocations]
ORDER BY
[CreatedDateTime] ASC
)
SELECT
[TerminalId],
Keys = JSON_QUERY('['+ string_agg(json_query('{"Point":"' + Location.STAsText() + '","CreatedDateTime":"' + cast(CreatedDateTime as nvarchar(20)) + '"}'),',') + ']')
FROM
NewScores
But unfortunately I got this error:
Msg 1033, Level 15, State 1, Line 100
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
Instead of putting the order by inside the CTE, put it for the query below
WITH NewScores AS
(
SELECT
geography::STGeomFromText(Location.STAsText(), 4326) AS Location,
[CreatedDateTime],
[TerminalId]
FROM
[Magicar_Route].[dbo].[PacketLocations]
)
SELECT
[TerminalId],
Keys = JSON_QUERY('['+ string_agg(json_query('{"Point":"' + Location.STAsText() + '","CreatedDateTime":"' + cast(CreatedDateTime as nvarchar(20)) + '"}'),',') + ']')
FROM
NewScores
ORDER BY
[CreatedDateTime] ASC

SQL Pivot - take a changing date from column and make it a row header

I have a basic query that looks like this.
SELECT Database_Name,
FilingDate,
SUM(ISNULL([column1], 0) + ISNULL(column2], 0) +
ISNULL([column3], 0) + ISNULL([column4], 0)) AS Total
FROM SomeTable(NOLOCK)
GROUP BY Database_Name,
FilingDate
ORDER BY Database_Name,
FilingDate DESC
This query outputs results that look like this.
I would like to take the dates returned in the FilingDate column and use them as new column headers with the totals for each database and date being used as the row content. The end result should look like this:
My research suggests that a pivot is the best option but I'm struggling to find the right way to execute it as my dates change each day Any assistance would be appreciated.
If this is MS SQL, you can use a dynamic pivot table. Here is a solution using your query (should work, but I don't have the base data to test it).
SELECT Database_Name,
FilingDate,
SUM( ISNULL(column1 ,0) +
ISNULL(column2],0) +
ISNULL([column3],0) +
ISNULL([column4],0)
) AS Total
INTO #T1
FROM SomeTable(NOLOCK)
GROUP BY Database_Name,
FilingDate
DECLARE #PivotColumnHeaders varchar(MAX)
SELECT #PivotColumnHeaders =
COALESCE(
#PivotColumnHeaders + ',[' + CAST(UC.FilingDate AS NVARCHAR(10)) + ']',
'[' + CAST(UC.FilingDate AS NVARCHAR(10)) + ']'
)
FROM (SELECT FilingDate FROM #T1 GROUP BY FilingDate) UC
DECLARE #PQuery varchar(MAX) = '
SELECT * FROM (SELECT Database_Name, FilingDate, Total FROM #T1 T0) T1
PIVOT (SUM([Total]) FOR FilingDate IN (' + #PivotColumnHeaders + ') ) AS P'
EXECUTE (#PQuery)
DROP TABLE #T1

Query Filter based on condition

I have this query (SQL Server 2019) and I actually wanted to add a filter to it to show only items where IssueStatusID = 1 (This column is based on int Data Type)
Can anyone help with this or point me in the right direction?
SELECT ID,
STRING_AGG(TRY_CONVERT(varchar, Issue#, 101) + ': ' + Notes + CHAR(13) + CHAR(10) + CHAR(13), CHAR(10)) WITHIN GROUP (ORDER BY Issue# DESC) AS IssueNotes
FROM (SELECT DISTINCT
ac4.ID,
nd.Notes,
nd.Issue#,
nd.IssueStatusID
FROM dbo.IssueTracking AS nd
INNER JOIN dbo.StatusUpdates AS ac4 ON ac4.ID = nd.ReleaseTrackerID) AS vNotes
GROUP BY ID;
Add the WHERE clause as shown below. The WHERE clause limits the data being returned.
SELECT ID,
STRING_AGG(TRY_CONVERT(varchar, Issue#, 101) + ': ' + Notes + CHAR(13) + CHAR(10) + CHAR(13), CHAR(10)) WITHIN GROUP (ORDER BY Issue# DESC) AS IssueNotes
FROM (SELECT DISTINCT
ac4.ID,
nd.Notes,
nd.Issue#,
nd.IssueStatusID
FROM dbo.IssueTracking AS nd
INNER JOIN dbo.StatusUpdates AS ac4 ON ac4.ID = nd.ReleaseTrackerID
WHERE nd.IssueStatusID = 1
) AS vNotes
GROUP BY ID;

SQL Server 2008 Alter Table Concatenate

I need to concatenate 2 ints and a varchar column into plan_no so it would look like this
Any help would be much appreciated.
We can try using CONVERT here to convert the numeric fields into text:
SELECT
CONVERT(varchar(10), lot) + '-' + forester + '-' +
CONVERT(varchar(10), year) AS plan_no
FROM yourTable;
If you want an update, then just use:
UPDATE yourTable
SET plan_no = CONVERT(varchar(10), lot) + '-' + forester + '-' +
CONVERT(varchar(10), year);
You need to do conversions :
select *, cast(lot as varchar(255)) + '-' +forester + '-' +cast([year] as varchar(5)) as plan_no
from table t;
You can alter your DDL :
alter table t
add plan_no as (cast(lot as varchar(255)) + '-' +forester + '-' +cast([year] as varchar(5)))
Edit :
update t
set plan_no = cast(lot as varchar(255)) + '-' +forester + '-' +cast([year] as varchar(5))
where plan_no is null;
I think you want to update data in your current table:
UPDATE TableName
SET plan_no = cast(lot as nvarchar(50)) + '-' + forester + '-' + cast([year] as nvarchar(50))
Please note: if lot, forester or year columns can contain nulls then you need to wrap values by ISNULL() function

Issue with NULL values in creating a view in sql table

I am working on a SQL View over a table with different values in it. I am trying to combine two columns in a table to be displayed in a single column of a view separated by a '/'.
For Example I have two columns in a table named In and inVolume with values for 'In' being
1,2,NULL
and for 'inVolume ' being
NULL, 100, 200
and the results I was expecting are 1/(NULL or Empty), 2/100, (NULL or Empty)/200 but when I created the view and ran it the results were (NULL or Empty), 2/100, (NULL or Empty). The issue being it is making the column in view as NULL if any of the columns In or inVolume in the table are NULL.
I created the following view
SQL View
CREATE VIEW [dbo].[Result]
AS
with CTE as(
SELECT distinct
CC.Product,
CC.Term,
CC.TermID,
iCC.In,
iCC.Out,
iCC.inVolume,
iCC.outVolume
FROM Cust CC
CROSS APPLY (SELECT TOP 3
In,
Out,
inVolume,
outVolume
FROM Cust iCC
WHERE CC.Term = iCC.Term and CC.Product = iCC.Product
ORDER BY iCC.In DESC, iCC.Out ASC) iCC)
select Product, Term, cast(inVolume as varchar(99)) + '/' + cast(In as varchar(99)) as value, inlabel as label from CTE
union
select Product, Term, cast(Out as varchar(99)) + '/' + cast(outVolume as varchar(99)), outlabel from CTE
GO
Any better way to deal with this?
Replace this:
cast(outVolume as varchar(99))
Whit this:
cast((CASE WHEN outVolume IS NULL THEN 0 ELSE outVolume END) as varchar(99))
On every field. Hope this help.
Use IsNull to enable nullable-column concatentation
select Product, Term,
IsNull(inVolume, '(NULL OR EMPTY)', cast(inVolume as varchar(99))) + '/' +
IsNull(In, '(NULL OR EMPTY)', cast(In as varchar(99))) as value,
inlabel as label from CTE
UNION
select Product, Term,
IsNull(Out, '(NULL OR EMPTY)', cast(Out as varchar(99))) + '/' +
IsNull(outVolume, '(NULL OR EMPTY)', cast(outVolume as varchar(99))),
outlabel from CTE
Replace
cast(inVolume as varchar(99)) + '/' + cast(In as varchar(99))`
with
cast(inVolume as varchar(99)) + '/'
+ ISNULL(cast(In as varchar(99)), '(NULL OR EMPTY)')`
and
cast(Out as varchar(99)) + '/' + cast(outVolume as varchar(99))`
with
cast(Out as varchar(99)) + '/'
+ ISNULL(cast(outVolume as varchar(99)), '(NULL OR EMPTY)')