Crosstab data in SQL results - sql

I got this kind of data on my db.
I need to show a result like this:
Using crystal reports this is doable. Hope someone can help me write a query for this.

This is not something that you would normally do using SQL, much better to implement in the application. But if you wanted to do it then you could do something like this:
SELECT Item,
[01/01/2016 - Unique Emp ID] = Count(Distinct iif([Date] = Convert(date, '01-01-2016', [Emp ID], NULL)),
[01/01/2016 - Sum Qty] = Sum(iif([Date] = Convert(date, '01-01'2016', [Qty Bought], NULL)),
[02/01/2016 - Unique Emp ID] = Count(Distinct iif([Date] = Convert(date, '02-01-2016', [Emp ID], NULL)),
...
FROM MyTable;
The downside here is that the column headings are fixed. That's why you should do this in the application.

Related

how do I create a new column based on 3 other columns in my select statement [duplicate]

This question already has answers here:
case statement based on 3 columns in 1 table
(4 answers)
Closed 3 years ago.
I want to create a new column in my sql statement that has a flag of a 'Yes' if the MRN and TF_Group are duplicated but the PathID is different (see the link below showing my output)
I have been able to create the column in excel (see the link below and in particular the column titled 'Flag') but just can't think of how to replicate it in sql server. The function that i used to create the 'Flag' column was =if(and(b2=b3,d2=d3,a2<>a3),"Yes","No")
I just don't know how to recreate a similar thing in sql server. Below is the sql code that i have used to extract the data that you can see in the link at the bottom of this post.
Anyone got any ideas?
select DISTINCT
[Pathway ID] PathID,
MRN,
DENSE_RANK() OVER(PARTITION BY mrn ORDER BY [Pathway ID]) RK,
[Treatment Function Group] TF_GROUP,
'' [Flag]
from [HRS_RTT].[dbo].[tbl_PMM_IncompletePTL_CG_Snapshot]
where convert(date,censusdate) between '03-jun-19' and '09-jun-19'
AND MRN IS NOT NULL
AND [Treatment Function Group] IS NOT NULL
order by
MRN,
[Pathway ID]
Here is a solution to your problem as described. It uses the T-SQL LEAD function to compare across rows. Note that I did not include the DISTINCT criteria from your original query as it is not clear what you are trying to accomplish with that.
However, as I said in the comment, I don't think this is necessarily how you want to do this. You may want to give some more thought to your requirements and see if you can come up with a better way to fulfill them.
select
PathID,
MRN,
TF_Group,
case
when MRN = Next_MRN and TF_Group = Next_TF_Group and PathID <> Next_PathID then 'Yes'
else 'No'
end as Flag
from (
select
[Pathway Id] as PathID,
MRN,
[Treatment Function Group] as TF_Group,
lead([Pathway Id]) over (order by MRN, [Pathway ID]) as Next_PathID,
lead(MRN) over (order by MRN, [Pathway ID]) as Next_MRN,
lead([Treatment Function Group]) over (order by MRN, [Pathway ID]) as Next_TF_Group
from tbl_PMM_IncompletePTL_CG_Snapshot
) x
order by MRN, PathID
As suggested in the comments:
select DISTINCT
[Pathway ID] PathID,
MRN,
CASE WHEN MRN = MRN AND [Treatment Function Group] = [Treatment Function Group] AND [Pathway ID] <> [Pathway ID] THEN 'YES' ELSE 'NO' END [Flag]
from [HRS_RTT].[dbo].[tbl_PMM_IncompletePTL_CG_Snapshot]
where convert(date,censusdate) between '03-jun-19' and '09-jun-19'
AND MRN IS NOT NULL
AND [Treatment Function Group] IS NOT NULL
order by
MRN,
[Pathway ID]

Merge two SQL data tables in asp.net website using vb.net in code behind

I can't seem to find a solution that fits.
Here is the situation. I have a two SQL queries from the same table each with a different where clause.
Table A uses this SQL statement:
Select jo.AssemblySeq As Assm,
jo.OprSeq As [OP Center #],
jo.WCCode As WC,
Convert(Varchar, jo.DueDate, 101) As [Due Date],
ja.RequiredQty As Qty,
jo.QtyCompleted As [Qty Comp],
jo.OpComplete As OpComplete
From JobOper jo
Join JobAsmbl ja
On jo.JobNum = ja.JobNum
And jo.AssemblySeq = ja.AssemblySeq
Where jo.JobNum Like '236087.%'
And ja.AssemblySeq <> 0
Order By jo.AssemblySeq;
And returns this data:
Table B uses this SQL query:
Select jo.AssemblySeq As Assm,
jo.OprSeq As [OP Center #],
jo.WCCode As WC,
Convert(Varchar, jo.DueDate, 101) As [Due Date],
jo.QtyPer As QTY,
jo.QtyCompleted As [Qty Comp],
jo.OpComplete As OpComplete
From JobOper jo
Join JobAsmbl ja
On jo.JobNum = ja.JobNum
And jo.AssemblySeq = ja.AssemblySeq
Where jo.JobNum Like '236087.%'
And ja.AssemblySeq = 0
Order By jo.AssemblySeq;
And returns this data:
What I need to do is merge these two tables so that I have columns called Assm, OP Center #, WC, Due Date, Qty, Qty Completed, OpComplete. My problem is that the where clause for the query for table A has ja.AssemblySeq <> 0 and the where clause for the query for table B has ja.AssemblySeq = 0.
I need all the lines from both queries. I am not sure if I need some type of Join or if it would involve sub queries?
A simple UNION ALL will help as below:
Select * from Query1
Union All
Select * from Query2
You don't need to do a UNION ALL at all. You can do this with one single query, without the need to hit the table twice.
Your queries are identical with the exception of the column selected based on the value of ja.AssemblySeq. You can just remove the WHERE clause altogether and make the Qty column a CASE expression.
Select jo.AssemblySeq As Assm,
jo.OprSeq As [OP Center #],
jo.WCCode As WC,
Convert(Varchar, jo.DueDate, 101) As [Due Date],
Case When ja.AssemblySeq = 0
Then jo.QtyPer
Else ja.RequiredQty
End As Qty,
jo.QtyCompleted As [Qty Comp],
jo.OpComplete As OpComplete
From JobOper jo
Join JobAsmbl ja
On jo.JobNum = ja.JobNum
And jo.AssemblySeq = ja.AssemblySeq
Where jo.JobNum Like '236087.%'
Order By jo.AssemblySeq;

sql distinct with multiple fields requried

I'm using Advantage Database Server by Sybase. I need to elimiate duplicate addbatch's from my report, but having trouble pulling up just distinct records. Any idea what I am missing?
here is what I am using
SELECT DISTINCT
SI.[addbatch] as [Batch#],
SI.[current account #] as [Account],
SI.[status date] as [Status Date],
SI.[SKU] as [SKU],
AC.[email address] as [Email]
FROM salesinventory SI, accounts AC
WHERE AC.[account #]=SI.[current account #] and [Status Date] > '6/1/2015'
I still get duplicate addbatch's though. I'm not sure where I am going wrong! Thanks in advance! Wasn't even sure how to google this question!
The problem is that you need to check uniqueness of a single column and that's not actually what your code is performing. Try this
SELECT *
FROM (SELECT SI.[addbatch] as [Batch#],
SI.[current account #] as [Account],
SI.[status date] as [Status Date],
ETC,
ROW_NUMBER() OVER (PARTITION BY [Batch#]) AS RowNumber
FROM salesinventory SI, accounts AC
WHERE AC.[account #]=SI.[current account #] and [Status Date] > '6/1/2015') as rec
WHERE rec.RowNumber = 1
-- The following code is generic to de-duplicate records, modify to suit your need.
select x.[Well_Name] as nameX
, x.[TestDate] as dateX
from (
SELECT count(*) as dup
,[Well_Name]
,[TestDate]enter code here
FROM [dbo].[WellTests]
group by [TestDate] ,[Well_Name] ) x
where dup > 1
If you want to have unique batch numbers in your result, you have to GROUP BY the batch field only.
Something like this should work:
SELECT
SI.[addbatch] as [Batch#],
MIN(SI.[current account #]) as [Account],
MIN(SI.[status date]) as [Status Date],
MIN(SI.[SKU]) as [SKU],
MIN(AC.[email address]) as [Email]
FROM salesinventory SI, accounts AC
WHERE AC.[account #]=SI.[current account #] and [Status Date] > '6/1/2015'
GROUP BY
SI.[addbatch]
You didn't say how you want to aggregate the other columns, just replace MIN with something that makes more sense for you, like SUM or COUNT, etc.
There is a topic about grouping in the documentation.
PS: SELECT DISTINCT is (basically) just a shorter way to GROUP BY on all columns without any aggregation.

Where do i place the 'Max' function in my SQL query to display the most recent 'LastCallBack'?

My boss has asked me to place a 'Max' function of somesort into my statement so that when the table displays it comes up with the most recent 'LastCallBack' , I am not looking for a answer just someone to give me some guidance on this as i've searched SO and can't find something to answer my question.
Here is my code.
Select Cdf_Code_Tx, ProjectNo, Convert (Date, [Last Call Back], 103)
As LastCallBack, (CDF_New_des1_Tx+CDF_New_des2_Tx) As Description
From Products
Inner Join SpecDetails
On CDF_Code_Tx = ProductRef
Inner Join Projects2
On ProjectNo = PID
Order By Convert (Date, [Last Call Back], 103) Desc
Thank you in advance.
You can add a where condition like:
WHERE [Last Call Back] = (SELECT MAX([Last Call Back])
FROM table_where_last_call_back_column_is)

SQL aggregate and other fields showing in query

I have a query, where I need the MIN of a DateTime field and then I need the value of a corresponding field in the same row.
Now, I have something like this, however I cannot get Price field without putting it also in an aggregate clause, which is not what I want.
SELECT MIN([Registration Time]), Price FROM MyData WHERE [Product Series] = 'XXXXX'
I need the MIN of the Registration Time field and then I just want the corresponding Price field for that row, however how do I show that?
I do also need my WHERE clause as shown.
I'm sure I've overlooked something really obvious. Using SQL Server 2008
If you want just one record with [Registration Time], Price, it'd be as simple as this:
select top 1 [Registration Time], Price
from MyData
where [Product Series] = 'XXXXX'
order by [Registration Time]
If you want minimum [Registration Time] and corresponding Price for all [Product Series], then there's a few approaches, for example, using row_number() function:
with cte as (
select
[Registration Time], Price,
row_number() over(partition by [Product Series] order by [Registration Time]) as rn
from MyData
)
select
[Registration Time], Price, [Product Series]
where rn = 1