I have a table studentexamrecord
Name|Module1|Module2|Module3|Total
A-------RT-----PASS---PASS
B-------RC-----RC------RT
C-------RT-----PASS----RC
I would like to calculate the total number of column that contains RT and RC at the total column.
What should i do?
Please give it a try:
SELECT
Name,
Module1,
Module2,
Module3,
(
(Module1 = 'RT' OR Module1 = 'RC')+
(Module2 = 'RT' OR Module2 = 'RC')+
(Module3 = 'RT' OR Module3 = 'RC')
) AS Total
FROM your_table
Note: MySQL boolean expression resolves into 0/1. Let's say if Module1 is RC or RT then the following expression returns 1
(Module1 = 'RT' OR Module1 = 'RC') returns 1
otherwise it returns zero (0)
This query returns the sum of total in record that contain module1 = RC edit it to much you condition :
Select
sum(if(module1 = RT, total, 0))
from
studentexamrecord;
Related
I am trying to convert the following T-SQL statement into Linq to Sql but am having trouble with the subtraction from the count. The final select will be a single row and single column (int)
I have done the SQL in two ways (sub-query and by JOIN/GROUP) which both return the same result, although I think the former might be the 'easier' option...
SQL 1 using a sub-query...
SELECT e.Places - ( SELECT COUNT(*) FROM [Event Participants] ep WHERE ep.E__ID = x AND ep.EP_STAT IN ('B','C')) AS AvailablePlaces
From Events e
WHERE e.E__ID = x
SQL 2 using GROUP BY and JOIN...
SELECT e.Places - COUNT(ep.E__ID) AS AvailablePlaces
FROM Events e
JOIN [Event Participants] ep ON e.E__ID = ep.E__ID
WHERE e.E__ID = x AND ep.EP_STAT IN ('B','C')
GROUP BY e.Places
Something like
var array = new string[] { "B", "C" };
var result = (from e in Event where e.E__ID == x
let count = (from ep in Event_Participants
where ep.E__ID == e.E__ID &&
array.Contains(ep.EP_Stat)
select ep).Count()
select e.Places - count
)
.Single();
Depending on your model, it might be possible to use navigation properties in the subquery.
I have the following SQL query in an SSRS dataset:
SELECT c.Id
, c.LastName + ', ' + c.FirstName AS CustomerName
, r.PurchaseDate
FROM tblCustomer c
JOIN Receipt r ON r.CustomerId = c.Id
WHERE StoreId = #storeId
I also have three parameters for the report: start date, end date, and customer. The workflow is: select a start date, select an end date, then the above dataset is filtered to only show the customer names in the multi-select dropdown parameter that have a receipt date within the start and end dates. The problem is, when customer has multiple receipts within the date range, the customer shows up more than once in the dropdown parameter. I copied the VB code that filters out the duplicates:
Public Shared Function RemoveDuplicates(parameter As Parameter) As String()
Dim items As Object() = parameter.Value
System.Array.Sort(items)
Dim k As Integer = 0
For i As Integer = 0 To items.Length - 1
If i > 0 AndAlso items(i).Equals(items(i - 1)) Then
Continue For
End If
items(k) = items(i)
k += 1
Next
Dim unique As [String]() = New [String](k - 1) {}
System.Array.Copy(items, 0, unique, 0, k)
Return unique
End Function
which works great, except that it only shows the Customer ID in the dropdown.
How do I get the multi-select dropdown to have the CustomerName as the label and the Customer Id as the value?
You can get around this by doing a cascading parameters.
I don't see where the start_date and end_date parameters are being used..
You can create another dataset, lets call it customers.
Your customer dateset query will be:
SELECT DISTINCT
c.Id
, c.LastName + ', ' + c.FirstName AS CustomerName
FROM tblCustomer c
JOIN Receipt r ON r.CustomerId = c.Id
WHERE StoreId = #storeId
-- and Receipt.somedate between #start_date and #end_date
Set your customer parameter to source it's data from this query. You will only ever have customers from the above select..
Go to the customer parameter.. available value -> customer data set
Set the values in there - value field will be ID and Label field will be name
Of course, your main dataset need to have #customerID filter along with #start_date and #end_date
I am stuck in a query I want to store sum result in a variable where status = 3, what happening right now is it store the value of last row and show it with all rows
Here is the query
SELECT
request_made_on,driver_id,
#sum_result = SUM(status = 3) AS complete_count,#sum_result,
SUM(status = 6) AS missed_count,
(status = 4) AS canceled_count,
sum(actual_fare),sum(discount)
from tb_engagements
group by date(request_made_on),driver_id;
and here is the screenshot,
second screenshot
I'm guessing that you want the sum of all the values:
select request_made_on, driver_id,
(#sum_result := #sum_result + SUM(status = 3)) AS complete_count,
sum(status = 6) AS missed_count,
sum(status = 4) AS canceled_count,
sum(actual_fare),
sum(discount)
from tb_engagements c cross join
(select #sum_result := 0) params
group by date(accept_time), driver_id;
Notes:
You don't need to return the value of the variable as well as the expression. The expression adds a column to the result set with the value.
You don't need if() to count values. MySQL has a nice short-hand, treating boolean expressions as integers in a numeric context.
See the SQL query below:
SELECT *
FROM
(SELECT
h.hotel_id AS id,h.hotel_city AS city,h.hotel_name AS hotelname,
h.hotel_star AS hotelcat, hwd.double_spl_rate, hwd.third_party_rate,
hwd.extra_bed_spl_rate, hwd.meal_plan_spl,
hwd.third_party_extra_bed, hwd.third_party_meal_plan,
hwd.room_category, hrd.hotel_rate_from, hrd.hotel_rate_to
FROM
hotels_list AS h
INNER JOIN
hotel_rate_detail AS hrd ON h.hotel_id = hrd.hotels_id
INNER JOIN
hotel_week_days AS hwd ON hrd.hotel_id = hwd.h_id
WHERE
(('2015-07-31' BETWEEN hrd.hotel_rate_from AND hrd.hotel_rate_to)
OR
('2015-08-01' BETWEEN hrd.hotel_rate_from AND hrd.hotel_rate_to)
)
AND (h.hotel_city = '1')
AND (hwd.double_spl_rate != 0 OR hwd.third_party_rate != 0)
AND (h.hotel_star = '4')
ORDER BY
hwd.double_spl_rate, hwd.third_party_rate ASC) AS result_table
GROUP BY
result_table.id
ORDER BY
result_table.double_spl_rate, result_table.third_party_rate ASC
LIMIT 0,5;
OUTPUT is attached below:
In the above output there are two columns double_spl_rate and third_party_rate which can be either 0 or a value greater than zero.
How can I create a virtual column alias which only contain values greater the zero. Let us suppose the column is final_rate which will contain values as
id | final_rate
533 | 3776
9228 | 3000
Yes, you can do this like so:
select
id,
case
when coalesce(double_spl_rate,0) = 0
then third_party_rate
else double_spl_rate
end as final_rate
from table
The coalesce operator will set double_spl_rate to 0 if it's null, and the case expression will return third_party_rate if double_spl_rate is 0.
If double_spl_rate cannot be null you can skip the coalesce part.
Note that the code above will always prefer the value in double_spl_rate and disregard the other value if both values are greater than 0. If you don't want this you could extend the logic in the case expression to account for that and return the sum of the values instead. Or you could simply just return third_party_rate + double_spl_rate in all cases.
Presently troubleshooting a problem where running this SQL query:
UPDATE tblBenchmarkData
SET OriginalValue = DataValue, OriginalUnitID = DataUnitID,
DataValue = CAST(DataValue AS float) * 1.335
WHERE
FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND ZEGCodeID IN
(SELECT ZEGCodeID FROM tblZEGCode
WHERE(ZEGCode = 'C004') OR
(LEFT(ZEGParentCode, 4) = 'C004'))
Results in the following error:
Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to float.
The really odd thing is, if I change the UPDATE to SELECT to inspect the values that are retrieved are numerical values:
SELECT DataValue
FROM tblBenchmarkData
WHERE FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND ZEGCodeID IN
(SELECT ZEGCodeID
FROM tblZEGCode WHERE(ZEGCode = 'C004') OR
(LEFT(ZEGParentCode, 4) = 'C004'))
Here are the results:
DataValue
2285260
1205310
Would like to use TRY_PARSE or something like that; however, we are running on SQL Server 2008 rather than SQL Server 2012. Does anyone have any suggestions? TIA.
It would be helpful to see the schema definition of tblBenchmarkData, but you could try using ISNUMERIC in your query. Something like:
SET DataValue = CASE WHEN ISNUMERIC(DataValue)=1 THEN CAST(DataValue AS float) * 1.335
ELSE 0 END
Order of execution not always matches one's expectations.
If you set a where clause, it generally does not mean the calculations in the select list will only be applied to the rows that match that where. SQL Server may easily decide to do a bulk calculation and then filter out unwanted rows.
That said, you can easily write try_parse yourself:
create function dbo.try_parse(#v nvarchar(30))
returns float
with schemabinding, returns null on null input
as
begin
if isnumeric(#v) = 1
return cast(#v as float);
return null;
end;
So starting with your update query that's giving an error (please forgive me for rewriting it for my own clarity):
UPDATE B
SET
OriginalValue = DataValue,
OriginalUnitID = DataUnitID,
DataValue = CAST(DataValue AS float) * 1.335
FROM
dbo.tblBenchmarkData B
INNER JOIN dbo.tblZEGCode Z
ON B.ZEGCodeID = Z.ZEGCodeID
WHERE
B.FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND (
Z.ZEGCode = 'C004' OR
Z.ZEGParentCode LIKE 'C004%'
)
I think you'll find that a SELECT statement with exactly the same expressions will give the same error:
SELECT
OriginalValue,
DataValue NewOriginalValue,
OriginalUnitID,
DataUnitID OriginalUnitID,
DataValue,
CAST(DataValue AS float) * 1.335 NewDataValue
FROM
dbo.tblBenchmarkData B
INNER JOIN dbo.tblZEGCode Z
ON B.ZEGCodeID = Z.ZEGCodeID
WHERE
B.FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND (
Z.ZEGCode = 'C004' OR
Z.ZEGParentCode LIKE 'C004%'
)
This should show you the rows that can't convert:
SELECT
B.*
FROM
dbo.tblBenchmarkData B
INNER JOIN dbo.tblZEGCode Z
ON B.ZEGCodeID = Z.ZEGCodeID
WHERE
B.FieldDataSetID = '6956beeb-a1e7-47f2-96db-0044746ad6d5'
AND (
Z.ZEGCode = 'C004' OR
Z.ZEGParentCode LIKE 'C004%'
)
AND IsNumeric(DataValue) = 0
-- AND IsNumeric(DataValue + 'E0') = 0 -- try this if the prior doesn't work
The trick in the last commented line is to tack on things to the string to force only valid numbers to be numeric. For example, if you wanted only integers, IsNumeric(DataValue + '.0E0') = 0 would show you those that aren't.