Result showing two rows to one row - sql

I wrote a query to count positive and negative results per day. My problem is that I am getting two rows per postivie to negative day.
I want one row with a positive and negative column for each day( no multiple days).
SELECT case([MsrSplatPositive]) when '0' then count([MsrSplatPositive]) end as 'Negative'
,case([MsrSplatPositive]) when '1' then count([MsrSplatPositive]) end as 'Positive'
,CONVERT(VARCHAR(10), f.NewsDate, 106) as 'Date'
FROM [News].[dbo].[Score] s
inner join [News].[dbo].[Feed] f
on f.ScoreId = s.Id
where f.NewsDate between dateadd(day,-30,GETDATE()) and GETDATE()
group by [MsrSplatPositive],CONVERT(VARCHAR(10), f.NewsDate, 106)

Remove MsrSplatPositive from the GROUP BY.
That is forcing the positive and negative results into different days.
And then use a SUM(CASE...) instead of CASE(COUNT...)
You have this in the SELECT:
case([MsrSplatPositive]) when '0' then count([MsrSplatPositive]) end as 'Negative'
and instead want this:
sum(CASE WHEN MsrSplatPositive = 0 THEN 1 ELSE 0 END) as 'Negative'
EDIT:
All fixed up should be something like:
SELECT SUM(CASE WHEN MsrSplatPositive = 0 THEN 1 ELSE 0 END) 'Negative'
,SUM(MsrSplatPositive 'Positive'
,CONVERT(VARCHAR(10), f.NewsDate, 106) as 'Date'
FROM News.dbo.Score s
INNER JOIN
News.dbo.Feed f on f.ScoreId = s.Id
WHERE f.NewsDate BETWEEN DATEADD(DAY,-30,GETDATE()) and GETDATE()
GROUP BY f.NewsDate

Try this...I haven't run the query but think this should achieve the result. I have modified your original query to return 0 instead of null in the positive and negative column. Then used the modified SQL as a temp table and grouped by the date values.
Select Sum(Temp.Negative), Sum(Temp.Positive), Temp.Date From
(
SELECT case([MsrSplatPositive]) when '0' then count([MsrSplatPositive])
else 0 end as 'Negative'
,case([MsrSplatPositive]) when '1' then count([MsrSplatPositive]
else 0) end as 'Positive'
,CONVERT(VARCHAR(10), f.NewsDate, 106) as 'Date'
FROM [News].[dbo].[Score] s
inner join [News].[dbo].[Feed] f
on f.ScoreId = s.Id
where f.NewsDate between dateadd(day,-30,GETDATE()) and GETDATE()
group by [MsrSplatPositive],CONVERT(VARCHAR(10), f.NewsDate, 106)
) Temp
Group By Temp.Date
Hope this helps.

Related

compare two different date ranges sales in two columns

I want to compare two different date ranges sales in two columns.. I am using query below but its giving wrong sales.. please correct my query
select s1.Itm_cd,s1.Itm_Name,Sum(S1.amount),Sum(s2.amount)
from salestrans s1,salestrans s2
where s1.Itm_cd = S2.Itm_cd
and S1.Tran_dt between '20181101' and'20181130'
and S2.Tran_dt between '20171101' and '20171130'
group by s1.Itm_cd,s1.Itm_Name
Order by s1.Itm_cd
I suspect that you want conditional aggregation here:
WITH cte AS (
SELECT
s1.Itm_cd,
s1.Itm_Name,
SUM(CASE WHEN s1.Tran_dt BETWEEN '20181101' AND '20181130'
THEN s1.amount ELSE 0 END) AS sum_2018,
SUM(CASE WHEN s1.Tran_dt BETWEEN '20171101' AND '20171130'
THEN s1.amount ELSE 0 END) AS sum_2017
FROM salestrans s1
GROUP BY
s1.Itm_cd,
s1.Itm_Name
)
SELECT
Itm_cd,
Itm_Name,
sum_2018,
sum_2017,
CASE WHEN COALESCE(sum_2017, 0) <> 0
THEN FORMAT(100.0 * (sum_2018 - sum_2017) / sum_2017, 'N', 'en-us')
ELSE 'NA' END AS growth_pct
FROM cte
ORDER BY
Itm_cd;
Please try the following
select s1.Itm_cd,s1.Itm_Name,Sum(S1.amount),Sum(s2.amount)
from salestrans s1,salestrans s2
where s1.Itm_cd = S2.Itm_cd
and Convert(Varchar(10),S1.Tran_dt,112) between '20181101' and'20181130'
and Convert(Varchar(10),S2.Tran_dt,112) between '20171101' and '20171130'
group by s1.Itm_cd,s1.Itm_Name
Order by s1.Itm_cd
Here the logic is that in right side while comparision you are providing only date and not any separator and time. The same way should be applied to the column in left side for comparision.
if(Convert(Varchar(10), getdate(),112) = '20181224')
print 'Matched'
else
print 'Not Matched'
if(getdate() = '20181224')
print 'Matched'
else
print 'Not Matched'
Here the output is Matched for first and Not Matched because in first case both side same format has been taken for comparison.

Complex Query SQL

I am currently working on an sql query where i am receiving data in three different rows, i really need the data in one single row
SELECT
substring(D.F1056, patindex('%[^0]%',D.F1056), 10) as Shop_Number,
REPLACE(CONVERT(VARCHAR(10), D.F254, 103), '/', '') AS Todays_Date,
SDP_TAB.F03 as Rayon,
[SDP_TAB].F04 as Famille,
CASE
WHEN D.F1034=3 THEN SUM(D.F64)
ELSE 0
END as Qty_Sold ,
CASE
WHEN D.F1034=3 THEN convert(DOUBLE PRECISION, SUM(D.F65)*100) * 10
ELSE 0
END as chiffre_daffaire_Caisse,
0 as montant_remisse_caisse,
CASE
WHEN D.F1034=3011 THEN SUM(D.F64)
WHEN D.F1034=3012 THEN SUM(D.F64)
ELSE 0
END as Qty_retour,
CASE
WHEN D.F1034=3011 THEN SUM(D.F65)
WHEN D.F1034=3012 THEN SUM(D.F65)
ELSE 0
END as Montant_Retour,
0 as Quantity,
CASE
WHEN D.F1034=3102 THEN SUM(D.F64)
ELSE 0
END as ClientCount,
F1034
FROM
[dbo].[RPT_ITM_D] D
LEFT OUTER JOIN [dbo].[POS_TAB] ON (D.F01=POS_TAB.F01)
LEFT OUTER JOIN [dbo].SDP_TAB ON (POS_TAB.F04=SDP_TAB.F04)
where
D.F1034 IN (3,3012,3011,3102)
AND
D.F254 = convert(varchar, getdate(), 101)
group by D.F1056,D.F254,SDP_TAB.F03,SDP_TAB.F04,D.F1034
My data is being populated as below
I am having three rows since i am having several condition for field F1034
Is there a way to have the expected result as below
Try this. (Using max with calculated columns)
With resultData as (
—Put your original query here
)
Select Shop_Number, Todays_Date,rayon,famille
,max(Qty_Sold) Qty_Sold, max(chiffre_daffaire_Caisse) chiffre_daffaire_Caisse
,max(montant_remisse_caisse) montant_remisse_caisse,max(Qty_retour) Qty_retour,max(Montant_Retour) Montant_Retour
,max(Quantity)Quantity,max(ClientCount) ClientCount,max(F1034) F1034
From resultData
group by Shop_Number, Todays_Date,rayon,famille

SQL Return Value of Zero so filter remains

The query below works great except for one thing.
I am using the column as "WorkStream" as a filter in my end user report. Since it is a filter I need it to be there regardless of whether or not the query returns anything.
Of course I have to use the where clause as a filter within the query so that only certain tasks are returned.
The trouble is that when I have a workstream without any task_Significance items the workstream is removed and the report filter (Workstream) does not work.
What I need is a table that looks like this but if I have a missing workstream then it would put "0's" all the way across. But only if the workstream is missing would it return ONLY the filter name (so the report would have the filter and just show and empty table below the filter in the final report.
This is my code:
SELECT
p.[Workstream]
,T.[Task_Significance]
,COUNT(1) AS Total
,SUM(case when T.[TaskPercentCompleted] >= 100 then 1 else 0 end) AS Actual
,SUM(case when T.[TaskFinishDate] <= DATEADD(DAY, 8-DATEPART(DW, GETDATE()), Convert(date,getdate())) then 1 else 0 end) AS Planned
FROM [psmado].[dbo].[MSP_EpmProject_UserView] as P
join [PSMADO].[dbo].[MSP_EpmTask_UserView] as T
On T.[projectUID] = P.[projectUID]
WHERE
[Task_Significance] IN('Application', 'Data', 'Interface', 'End User Compute', 'Network', 'Compute Package', 'Data Center', 'CREWS Sites', 'App Design Review', 'Infra Design Review')
GROUP BY p.[EnterpriseProjectTypeUID], p.[Workstream],T.[Task_Significance]
Is there anyway to do this?
Use a left join and move your where clause to the on clause. This will return all p.[Workstream] and those t.Task_Significance that are in your in() list.
You can use coalesce() or isnull() to substitute a value for null when there are no matching t.Task_Significance.
select
p.[Workstream]
, coalesce(T.[Task_Significance], 'none') as Task_Significance
, count(1) as Total
, sum(case when T.[TaskPercentCompleted] >= 100 then 1 else 0 end) as Actual
, sum(case when T.[TaskFinishDate]
<= dateadd(day, 8 - datepart(dw, getdate()), Convert(date, getdate()))
then 1 else 0 end) as Planned
from [psmado].[dbo].[msp_EpmProject_UserView] as P
left join [psmado].[dbo].[msp_EpmTask_UserView] as T
on T.[projectuid] = P.[projectuid]
and [Task_Significance] in ('Application', 'Data', 'Interface'
, 'End User Compute', 'Network', 'Compute Package', 'Data Center'
, 'crews Sites', 'App Design Review', 'Infra Design Review')
group by
p.[EnterpriseProjectTypeuid]
, p.[Workstream]
, T.[Task_Significance]

How to return count in 2 columns?

I have this query. It should return Count for both AWARDED (1) and NOT AWARDED(0) works from works table.
Select Count(w.WorkID)as Total, w.IsAwarded, org.OrganizationName
From Works w
Inner Join MC_MemberShip.Membership.Organization org
ON org.OrganizationID= w.Organization_ID
where Convert(varchar(11), w.OpeningDate) >= Convert(varchar(11), #FromDate)
and Convert(varchar(11), w.OpeningDate) < DATEADD(day, 1, Convert(varchar(11), #ToDate))
and w.IsActive=1 and
ISNULL(w.IsAwarded,0)= 0 and w.Organization_ID= case when #OrgID= -1 then w.Organization_ID else #OrgID end
group by org.OrganizationName, w.IsAwarded
Now this query returns Total count for NOT AWARDED i.e. 0 only but i want to return count for AWARDED too in same query.
Organization TotalAwardedWorks TotalNotAwardedWorks
Town 1 1 2
Town 2 44 33
Your query should look something like this:
select org.OrganizationName,
Count(*) as Total,
sum(case when w.IsAwarded = 0 or w.IsAwarded is null then 1 else 0 end) as TotalNotAward,
sum(case when w.IsAwarded = 1 then 0 else 1 end) as TotalAward
from Works w Inner Join
MC_MemberShip.Membership.Organization org
on org.OrganizationID = w.Organization_ID
where w.OpeningDate >= #FromDate and
w.OpeningDate < dateadd(day, 1, #ToDate) and
w.IsActive = 1 and
(w.Organization_ID = #OrgId or #OrgID= -1)
group by org.OrganizationName;
Notes:
Do not convert dates to strings to perform comparisons. That is just perverse.
Generally, the use of case in the where clause is discouraged. The logic is more clearly represented using or.
You can get what you want by using case to put conditions in the aggregation functions.

SQL Query: Cannot perform aggregate functions on sub queries

I have the following SQL query
SELECT
[Date],
DATENAME(dw,[Date]) AS Day,
SUM(CASE WHEN ChargeCode IN (SELECT ChargeCode FROM tblChargeCodes WHERE Chargeable = 1) THEN Units ELSE 0 END) ChargeableTotal,
SUM(CASE WHEN ChargeCode IN (SELECT ChargeCode FROM tblChargeCodes WHERE Chargeable = 0) THEN Units ELSE 0 END) NotChargeableTotal,
SUM(Units) AS TotalUnits
FROM
tblTimesheetEntries
WHERE
UserID = 'PJW'
AND Date >= '2013-01-01'
GROUP BY
[Date]
ORDER BY
[Date] DESC;
But I get the error message:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
Because I am using sub queries in the Case Else Summation.
How can I revise my query to get 2 x Sums of [Units] one for Chargeable = true, and one for Chargeable = false, even though the Chargeable field is in a different table to all the other information. The two tables are linked by ChargeCode which appears in both tblTimesheetEntries and tblChargeCodes.
Have you tried joining the tables on the chargeCode:
SELECT e.[Date],
DATENAME(dw,e.[Date]) AS Day,
SUM(CASE WHEN c.Chargeable = 1 THEN e.Units ELSE 0 END) ChargeableTotal,
SUM(CASE WHEN c.Chargeable = 0 THEN e.Units ELSE 0 END) NotChargeableTotal,
SUM(e.Units) AS TotalUnits
FROM tblTimesheetEntries e
LEFT JOIN tblChargeCodes c
on e.ChargeCode = c.ChargeCode
WHERE e.UserID = 'PJW'
AND e.Date >= '2013-01-01'
GROUP BY e.[Date]
ORDER BY e.[Date] DESC;