How to create a kql query between dates - kql

I am new to KQL and I am struggling to create a report that shows closed tickets between specific dates.
I've tried this query but no results:
SELECT COUNT('Tickets.Ticket ID') as closed, 'Tickets.Ticket ID', 'Tickets.Full Name',
'Tickets.Subject', 'Tickets.Priority', 'Tickets.Creation Date', 'Tickets.Resolved Date' FROM 'Tickets'
WHERE 'Tickets.Is Resolved' = '1' AND 'Tickets.Status' = 'Closed' AND 'Tickets.Resolved Date' = '2020-
05-01' and 'Tickets.Department' = 'cloud Services' multigroup BY 'Tickets.Resolved Date':Day,
'Tickets.Owner'

I assume that you are using Azure Data Explorer to run this query, if so it seems that you are looking for something like this:
Tickets
| where IsResolved == 1 and Status=="Closed" and startofday(ResolvedDate) == datetime(2020-05-01) and Department == "cloud Services multi"
| summarize closed = count() by Owner
But the SQL is unclear since some columns in the select clause are not specified in the group by.

This is the code I used and it works:
SELECT COUNT('Tickets.Ticket ID') as closed, 'Tickets.Ticket ID', 'Tickets.Full Name',
'Tickets.Subject', 'Tickets.Priority', 'Tickets.Creation Date', 'Tickets.Resolved Date'
FROM 'Tickets' WHERE 'Tickets.Status' = 'Closed' AND 'Tickets.Resolved Date' >='2020-
05-25' and 'Tickets.Resolved Date' <='2020-05-26' AND 'Tickets.Department' = '
TeamName' multigroup BY 'Tickets.Resolved Date':Day, 'Tickets.Owner'

Related

Troubleshooting Conditional Grouping with CASE (SQL Server 2008)

I'm hoping that someone is willing to help. I'm new to SQL and struggling to get a simple query debugged.
I want to create a simple frequency table to see how many values are missing (i.e. = 00000000) for the ArrestDate field.
SELECT
CASE WHEN ArrestDate=00000000 THEN 'NO DATE' ELSE 'HAS DATE' END AS HasDate,
CASE WHEN ArrestDate=00000000 THEN 0 ELSE 1 END as nDate
FROM ARREST_INFO
--GROUP BY HasDate
--GROUP BY CASE WHEN ArrestDate=00000000 THEN 'NO DATE' ELSE 'HAS DATE' END
Lines 1-4 parse without errors (output below).
Line 5 returns: Invalid column name 'HasDate'.
Line 6 returns: 'ARREST_INFO.ArrestDate' is invalid in the select
list because it is not contained in either an aggregate function or
the GROUP BY clause.
Since lines 1-4 run properly, I tried wrapping them inside another SELECT statement but this also elicits an error ("Invalid column name 'HasDate'.")
SELECT * FROM (
SELECT
CASE WHEN ArrestDate=00000000 THEN 'NO DATE' ELSE 'HAS DATE' END AS HasDate,
CASE WHEN ArrestDate=00000000 THEN 0 ELSE 1 END as nDate
FROM ARREST_INFO
)
GROUP BY HasDate
--GROUP BY CASE WHEN ArrestDate=00000000 THEN 'NO DATE' ELSE 'HAS DATE' END
Sadly, I can't update the SQL Server version. I'd be very grateful for any insight!
This answer to a previous question helped me figure out at least part of my problem. My Select statement referred to 2 columns, (nDate and HasDate), but my Group By statement only referred to one of them, so SQL didn't have enough information to determine how to display the unaggregated column data.
#Bill Karwin wrote:
https://stackoverflow.com/a/13999903/9499084
This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).
I'm still not sure why SQL doesn't recognize the new column defined in the Select statement (HasDate) when it's redeployed in the Group By statement, but at least I have functioning code now -- see screenshot below for results.
Here's my updated code:
SELECT
CASE WHEN ArrestDate=00000000 THEN 'NO DATE' ELSE 'HAS DATE' END AS HasDate,
SUM(CASE WHEN ArrestDate=00000000 THEN 0 ELSE 1 END) AS nDate,
COUNT(*) as TotalCases
FROM ARREST_INFO
GROUP BY CASE WHEN ArrestDate=00000000 THEN 'NO DATE' ELSE 'HAS DATE' END
enter image description here

I want to select multiple rows but print a message next to a few of them with a specific value in SQL

I am trying to print all the patients and what illness name they suffer from. If a patient suffers from 'Love sickness' it is supposed to print 'Critical condition' next to it. How do I do this without altering the table?
This is what I have so far
SELECT patientName, illnessName
FROM Patient
JOIN Suffers ON Suffers.patientID = Patient.patientID
I was thinking I could use SELECT patientName, illnessName, 'Critical condition' AS condition but I don't know how to do that for specifically those with 'Love sickness'
Some help would be appreciated :)
It sounds like you just need to add a conditional piece of text to the illnessName. If that's the case the following should work:
SELECT p.patientName,
s.illnessName + case when s.illnessName='Love sickenss' then ' Critical condition' else '' end as illnessName
FROM Patient p
JOIN Suffers s ON s.patientID = p.patientID
Use case when to add 1 or multiple conditions.
In the example below i have added love sickness and one random value i.e sickness 2. If you have only one then you can remove it, but if you have more than 1 you can just add more when statement.
in the else statement you will have final condidion if you want. I passed a string value, but if you would want to ignore that then you can just doe else end
SELECT patientName,
illnessName,
case when illnessName = 'Love sickness' then 'Critical Condition'
when illnessName = ' sickness 2' then ' less critical'
........
else 'No illness condition specified' end as condition_level
FROM Patient
JOIN Suffers ON Suffers.patientID = Patient.patientID

Display multiple rows in a single row

I have been trying to achieve this:
Instead I am getting similar but NOT the result I'm hoping for:
In thos result that I got from my query, I have rows repeating the SAME thing. For example, if you look at the first 4 results that I highlighted, I want the 1st row to appear and the next 3 to disappear, just like in the first image attached, NO repetition.
I have tried my ways but have got nothing. As in the first image attached, that is the kind of result I am looking for. Kind of nested rows in the last column. Below is what I have tried. I am also attaching a link to my .sql file for ease if anyone can help me with this problem (link). I am using MS SQL.
SELECT cj.completed_job_id AS 'Job Card No.',
c.cus_name AS 'Customer',
c.cus_address AS 'Address',
jt.job_type AS 'Job Type',
cj.no_of_days AS 'No. of Days',
CONCAT(jm.mat_quantity, ' ', jm.mat_type) AS 'Materials Used'
FROM completed_jobs cj
JOIN customers c
ON cj.customer_id = c.customer_id
JOIN job_types jt
ON cj.job_type = jt.job_type
JOIN job_materials jm
ON cj.completed_job_id = jm.completed_job_id;
You can select all of columns without "material used" and make subquery that contains only "material used" for that row.
In that subquery you can convert result to xml to put results into one cell and in next step replace xml tags.
Not very elegant but working - part of SQL below:
SELECT cj.completed_job_id AS 'Job Card No.',
c.cus_name AS 'Customer',
c.cus_address AS 'Address',
jt.job_type AS 'Job Type',
cj.no_of_days AS 'No. of Days',
(SELECT CONCAT(jm.mat_quantity, ' ', jm.mat_type) as material FROM job_materials jm WHERE cj.completed_job_id = jm.completed_job_id FOR XML AUTO) AS 'Materials Used'
FROM completed_jobs cj
JOIN customers c
ON cj.customer_id = c.customer_id
JOIN job_types jt
ON cj.job_type = jt.job_type

SQL AverageIFS Equivalent for Query

So I'm extremely new to using SQL. This syntax formatting is offensive but I am editing it in notepad and can't figure out a better alternative. I want it in the .dqy format but I don't know how else to edit. So if you have a suggestion please advise..
A general description: There is that SUM(CASE WHEN ...) portion of code below that I'm trying to get to work. I'm making an exception report, and I want another column that is the conditional average based on my concatenated value exclusive of that entry. IE, in Excel this is an easy formula (Column I):
=+IFERROR(AVERAGEIFS(H:H,C:C,[#Cust],A:A,"<>"&[#[Order Number]]),0)
Except I want to have it pull as part of the query.
Here is a picture of the output:
Here is my SQL. Again I know formatting stinks if there is a different program than notepad that I can edit a .dqy in please advise. Also, what do those 3's mean in the 6th line of my code. I took a query from something else and have been modifying it into this project.
XLODBC
1
DRIVER=SQL Server;
SERVER=*OMIT*;
UID=*OMIT*;
Trusted_Connection=Yes;
APP=Microsoft Office 2010;
WSID=*OMIT*;
DATABASE=*OMIT*
SELECT DISTINCT RMORHP.ORHORDNUM AS 'Order Number',
RMORHP.ORHCRTDTE AS 'Order Create Date',
CONCAT(RMORHP.ORHCUSCHN, '-', RMORHP.ORHCUSNUM) AS 'Cust',
RMORHP.ORHCUSCHN AS 'Chain ID',
RMORHP.ORHCUSNUM AS 'Cust ID',
RMCUSP.CUSCUSNAM AS 'Customer',
RMORHP.ORHCRTUSR AS 'Created By',
RMORHP.ORHORDQTY AS 'Units Ordered',
SUM(CASE
WHEN RMCUSP.CUSCUSNAM = RMCUSP.CUSCUSNAM
THEN RMORHP.ORHORDQTY
END)
GROUP BY RMCUSP.CUSCUSNAM AS 'Total Units'
FROM BIDW_DataLake.erms.RMORHP RMORHP,
BIDW_DataLake.eRMS.RMCUSP RMCUSP
WHERE (RMORHP.ORHCRTDTE BETWEEN ? AND ?)
AND RMCUSP.CUSCUSCHN = RMORHP.ORHCUSCHN
AND RMCUSP.CUSCUSNUM = RMORHP.ORHCUSNUM
AND RMCUSP.CUSDFTDCN = 505
enter
START date "yyyymmdd" enter END date "yyyymmdd"
3 3
Order Number Create Date Cust Chain ID Cust ID Customer Created By
It looks like you are trying to get the average order quantity for other order a customer has made during a given date range. To say it another way: The average of a given customer's orders not including the order in the current row.
If that's correct, you might try replacing the SQL portion of your query with this:
SELECT R1.ORHORDNUM AS 'Order Number',
R1.ORHCRTDTE AS 'Order Create Date',
CONCAT(RMORHP.ORHCUSCHN, '-', RMORHP.ORHCUSNUM) AS 'Cust',
R1.ORHCUSCHN AS 'Chain ID',
R1.ORHCUSNUM AS 'Cust ID',
RMCUSP.CUSCUSNAM AS 'Customer',
R1.ORHCRTUSR AS 'Created By',
R1.ORHORDQTY AS 'Units Ordered',
(SELECT AVG(R2.HORDQTY)
FROM BIDW_DataLake.erms.RMORHP R2
WHERE R2.ORHCUSNUM = R1.ORHCUSNUM
AND R2.ORHORDNUM <> R1.ORHORDNUM) as 'Total Units'
FROM BIDW_DataLake.erms.RMORHP R1,
BIDW_DataLake.eRMS.RMCUSP RMCUSP
WHERE (RMORHP.ORHCRTDTE BETWEEN ? AND ?)
AND RMCUSP.CUSCUSCHN = R1.ORHCUSCHN
AND RMCUSP.CUSCUSNUM = R1.ORHCUSNUM
AND RMCUSP.CUSDFTDCN = 505
The Total Units column is what is known as a correlated subquery. Consider researching that.
What makes this a bad answer:
I have no way of testing it, and I'm not 100% certain of the
MS-Query syntax where Excel connects with SQL Server.
MS-Query may not support correlated subqueries in this way.
I don't quite understand how the parameterized portion of the query works. That is, clearly it looks like the query is meant to ask for a start and end date and put those where the question marks go. I'm trusting that it works as-is. (Though, I suspect this is where your "3 3" is coming from.
So, probably vote this answer down and thrash me soundly for giving a bad answer, but maybe you will get something from it. I just thought it was too much to try to put in a comment.
I din't totally understand the example but for a general case you can use:
AVG(CASE WHEN [condition1] and [condition2] THEN [the value you want to average] Else NULL END).
This shoud return the average if the column fir all the rows that meet your conditions.

SQL Server 2008 query not executing properly

I have to run this query on my SQL Server 2008.
I need to join the 2 tables (Gasper_object and Ticket) and get the results where Gasper_object.id is also shown.
SELECT
TICKET.ACTION_CODE_KEY,
TICKET.OBJECT_KEY,
GASPER_OBJECT.ID,
CASE
WHEN ACTION_CODE_KEY IN (4,8) THEN 'OUT OF SERVICE'
WHEN ACTION_CODE_KEY IS NULL THEN 'IN SERVICE'
ELSE 'FAULTY SERVICE'
END "STATUS"
FROM
TICKET
INNER JOIN
GASPER_OBJECT ON ticket.OBJECT_KEY = GASPER_OBJECT.OBJECT_KEY
GROUP BY
ticket.object_key, GASPER_OBJECT.ID;
What should I do ?
UPDATE
This is what I received as a task to complete
IF THE ACTION_CODE IS 4 OR 8, THE COLOUMN NAME SHOULD BE OUT OF SERVICE
OTHERWISE IT SHOULD BE FAULTY SERVICE
IF THE OBJECT HAS NO TICKET AT ALL THEN IT'S IN SERVICE
GASPER_OBJECT.ID, STATUS SHOULD BE THE OUTPUT COLUMNS AFTER QUERYING
IF THE OBJECT HAS MORE THAN ONE TICKET WHICH APPLIES TO THE CRITERIA, USE DISTINCT
Just add rest of the columns to the group by.
SELECT
TICKET.ACTION_CODE_KEY,
TICKET.OBJECT_KEY,
GASPER_OBJECT.ID,
CASE
WHEN ACTION_CODE_KEY IN (4,8) THEN 'OUT OF SERVICE'
WHEN ACTION_CODE_KEY IS NULL THEN 'IN SERVICE'
ELSE 'FAULTY SERVICE'
END "STATUS"
FROM
TICKET
INNER JOIN
GASPER_OBJECT ON ticket.OBJECT_KEY = GASPER_OBJECT.OBJECT_KEY
GROUP BY
TICKET.ACTION_CODE_KEY, ticket.object_key, GASPER_OBJECT.ID;
In an aggregation query, all the columns not in the group by need to be arguments to aggregation functions. Here is an example of query that should at least run:
SELECT t.object_key, o.ID,
(CASE WHEN MAX(ACTION_CODE_KEY) IN (4, 8) THEN 'OUT OF SERVICE'
WHEN MAX(ACTION_CODE_KEY) IS NULL THEN 'IN SERVICE'
ELSE 'FAULTY SERVICE'
END) as STATUS
FROM TICKET t inner join
GASPER_OBJECT o
on t.OBJECT_KEY = o.OBJECT_KEY
group by t.object_key, o.ID;
Your question doesn't explain what you want to do, so this may or may not produce the results you expect.