Check if table has specific row value - sql-server

I have two tables called game and gameprogress. Gameprogress has a column called state that describes progress. Game is related to gameprogress trough an id.
Possible states is: 1,3,4 in gameprogress.
I want to find games without a state = 1 and without a state = 4. I've tried something like this:
select top 10 gp.gameid, count(gp.state) as dup
from gameprogress gp
join game g on g.id= gp.gameid
where g.gamestate != 2 and gp.state != 1
group by gp.gameid
having count(gp.state)>1

You can use CASE EXPRESSION in the HAVING clause :
SELECT TOP 10 g.gameid
FROM game g
LEFT JOIN gameprogress gp
ON g.id= gp.gameid
GROUP BY g.gameid
HAVING COUNT(CASE WHEN gp.state = 3 THEN 1 END) = COUNT(*)

Related

Why is this SQL case statement behaving like an OR statement?

Consider the following query:
declare #RentalId int = 1
SELECT
r.RentalId
,r.[Name]
,rt.TypeId
FROM dbo.Rental r
LEFT JOIN dbo.RentalRateType rt ON (
r.RentalId = rt.RentalId
AND rt.TypeId = (
case when rt.TypeId = 6 and coalesce(rt.[Max], rt.[Min]) is not null then 6
when rt.TypeId = 1 and coalesce(rt.[Max], rt.[Min] is not null then 1
else -1 end
))
WHERE r.RentalId = #RentalId
I'm attempting to return a single record/row. The particular rental in question has 2 records in the dbo.RentalRateType table, and when I run the above query, I get 2 results, but I want it to short circuit on the first match in the case where.
Basically, the end user can fill in multiple rate types, more than what you see in this example, and each of those types has a priority. 6 is the highest priority in the example.
So I'm getting this result:
RentalId | Name | TypeId
----------------------------
1 Super Car 6
1 Super Car 1
But if the type (6) exists, I would expect only the first row above returned.
I must be missing something silly. This works as expected:
case when 1=2 then 6
when 1=1 then 1
else -1 end
While I'm here, I'm open to a more efficient manner of handling this if exists.
Use an apply instead, these are an efficient way to get "top n" queries:
SELECT
r.RentalId
, r.[Name]
, oa.TypeId
FROM dbo.Rental r
OUTER APPLY (
SELECT TOP (1)
rt.TypeId
FROM dbo.RentalRateType rt
WHERE r.RentalId = rt.RentalId
ORDER BY
rt.TypeId DESC
) oa
WHERE r.RentalId = #RentalId

How to display only the MAX results from a query

I am new to writing MS SQL queries and I am trying to display only the record with the highest field named RecordVersion.
Below is the query that works but displays all records:
SELECT
PriceCalendars.PriceProgramID,
PriceCalendars.EffectiveDateTime,
PriceSchedules.Price,
PriceSchedules.PLU,
items.Descr,
PriceSchedules.LastUpdate,
PriceSchedules.LastUpdatedBy,
PriceSchedules.RecordVersion,
PriceSchedules.PriceScheduleUniqueID
FROM
PriceCalendars
INNER JOIN PriceSchedules ON PriceCalendars.PriceProgramID = PriceSchedules.PriceProgramID
INNER JOIN items ON PriceSchedules.PLU = items.PLU
WHERE
(PriceSchedules.PLU = 'SLS10100103')
AND (PriceCalendars.EffectiveDateTime = '2016-03-22')
Here are the query results:
PriceProgramID EffectiveDateTime Price PLU Descr LastUpdate LastUpdatedBy RecordVersion PriceScheduleUniqueID
1 2016-03-22 00:00:00.000 35.00 SLS10100103 Architecture Adult from NP POS 2015-01-22 07:53:15.000 GX70,83 9 569
1 2016-03-22 00:00:00.000 32.00 SLS10100103 Architecture Adult from NP POS 2014-02-25 16:22:46.000 GX70,83 5 86180
The first line of the results has RecordVersion being 9 and the second line results is 5, I only want the higher record displaying, the one that returned RecordVersion = 9.
Every time I try to use the MAX command I get errors or the group by and I have tried every example I could find on the web but nothing seems to work.
Using MS SQL 2012.
Thanks,
Ken
Try the following query which attempts to solve your problem by ordering the returned rows by RecordVersion DESC and then SELECTs just the first row.
SELECT TOP 1
PriceCalendars.PriceProgramID,
PriceCalendars.EffectiveDateTime,
PriceSchedules.Price,
PriceSchedules.PLU,
items.Descr,
PriceSchedules.LastUpdate,
PriceSchedules.LastUpdatedBy,
PriceSchedules.RecordVersion,
PriceSchedules.PriceScheduleUniqueID
FROM
PriceCalendars
INNER JOIN PriceSchedules ON PriceCalendars.PriceProgramID = PriceSchedules.PriceProgramID
INNER JOIN items ON PriceSchedules.PLU = items.PLU
WHERE
(PriceSchedules.PLU = 'SLS10100103')
AND (PriceCalendars.EffectiveDateTime = '2016-03-22')
ORDER BY
RecordVersion DESC
All group by columns should be in select ,that's the rule of group by.How group by works is for every distinct combination of group by columns,arrange remaining columns into groups,so that any aggregation can be applied,in your case I am not sure what group by columns are unique with out test date.here is one version which use row number which gives you the output desired
Remember ,order by last updated date is the one which decides rows order and assign numbers
WITH CTE
AS
(
SELECT PriceCalendars.PriceProgramID,
PriceCalendars.EffectiveDateTime,
PriceSchedules.Price,
PriceSchedules.PLU,
items.Descr,
PriceSchedules.LastUpdate,
PriceSchedules.LastUpdatedBy,
PriceSchedules.RecordVersion,
PriceSchedules.PriceScheduleUniqueID,
ROW_NUMBER() OVER (PARTITION BY PriceSchedules.RecordVersion ORDER BY PriceSchedules.LastUpdatedBy) AS RN
FROM
PriceCalendars
INNER JOIN PriceSchedules ON PriceCalendars.PriceProgramID = PriceSchedules.PriceProgramID
INNER JOIN items ON PriceSchedules.PLU = items.PLU
WHERE
(PriceSchedules.PLU = 'SLS10100103')
AND (PriceCalendars.EffectiveDateTime = '2016-03-22')
)
SELECT * FROM CTE WHERE RN=1

Counting duplicate items in different order

Goal:
To know if we have purchased duplicate StockCodes or Stock Description more than once on difference purchase orders
So, if we purchase Part ABC on Purchase Order 1 and Purchase Order 2, it should return the result of
PurchaseOrders, Part#, Qty
Purchase Order1, Purchase Order2, ABC, 2
I just don't know how to pull the whole code together, more to the point, how do I know if it's occurred on more than 1 Purchase Order without scrolling through all the results , may also have to do with Multiple (Having Count) Statements as I only seem to be doing by StockCode
SELECT t1.PurchaseOrder,
t1.MStockCode,
Count(t1.MStockCode) AS SCCount,
t1.MStockDes,
Count(t1.MStockDes) AS DescCount
FROM PorMasterDetail t1
INNER JOIN PorMasterHdr t2
ON t1.PurchaseOrder = t2.PurchaseOrder
WHERE Year(t2.OrderEntryDate) = Year(Getdate())
AND Month(t2.OrderEntryDate) = Month(Getdate())
GROUP BY t1.PurchaseOrder,
t1.MStockCode,
t1.MStockDes
HAVING Count(t1.MStockCode) > 1
Using responses I came up with the following
select * from
(
SELECT COUNT(dbo.InvMaster.StockCode) AS Count, dbo.InvMaster.StockCode AS StockCodes,
dbo.PorMasterDetail.PurchaseOrder, dbo.PorMasterHdr.OrderEntryDate
FROM dbo.InvMaster INNER JOIN dbo.PorMasterDetail ON
dbo.InvMaster.StockCode = dbo.PorMasterDetail.MStockCode
INNER JOIN dbo.PorMasterHdr ON dbo.PorMasterDetail.PurchaseOrder = dbo.PorMasterHdr.PurchaseOrder
WHERE YEAR(dbo.PorMasterHdr.OrderEntryDate) = YEAR(GETDATE())
GROUP BY dbo.InvMaster.StockCode, dbo.InvMaster.StockCode,
dbo.PorMasterDetail.PurchaseOrder, dbo.PorMasterHdr.OrderEntryDate
) Count
Where Count.Count > 1
This returns the below , which is starting to be a bit more helpful
In result line 2,3,4 we can see the same stock code (*30044) ordered 3 times on different
purchase orders.
I guess the question is, is it possible to look at If something was ordered more than once within say a 30 day period.
Is this possible?
Count StockCodes PurchaseOrder OrderEntryDate
2 *12.0301.0021 322959 2014-09-08
2 *30044 320559 2014-01-21
8 *30044 321216 2014-03-26
4 *30044 321648 2014-05-08
5 *32317 321216 2014-03-26
4 *4F-130049/TEST 323353 2014-10-22
5 *650-1157/E 322112 2014-06-24
2 *650-1757 321226 2014-03-27
SELECT *
FROM
(
SELECT h.OrderEntryDate, d.*,
COUNT(*) OVER (PARTITION BY d.MStockCode) DupeCount
FROM
PorMasterHdr h
INNER JOIN PorMasterDetail d ON
d.PurchaseOrder = h.PurchaseOrder
WHERE
-- first day of current month
-- http://blog.sqlauthority.com/2007/05/13/sql-server-query-to-find-first-and-last-day-of-current-month/
h.OrderEntryDate >= CONVERT(VARCHAR(25), DATEADD(dd,-(DAY(GETDATE())-1),GETDATE()),101)
) dupes
WHERE
dupes.DupeCount > 1;
This should work if you're only deduping on stock code. I was a little unclear if you wanted to dedupe on both stock code and stock desc, or either stock code or stock desc.
Also I was unclear on your return columns because it almost looks like you're wanting to pivot the columns so that both purchase order numbers appear on the same line.

TSQL while loop

UPDATE Houses
SET lStatus = U.codesum
FROM Houses H
JOIN (SELECT ref, SUM(code) AS codesum
FROM Users
GROUP BY ref) AS U ON U.ref = H.ref
The above code gets all users for every house (Houses table). SUMs the code column (Users table) for all users. And finally updates the result in lstatus column of the houses table.
My question is:
I need to rewrite the query which is NOT to sum the code column. Rather I want to create case statements. for example:
tempvar = 0 //local variable might be required
For each user {
If code == 1 then tempvar += 5
else if code == 2 then tempvar += 10
etc
tempvar = 0;
}
Once we have looped through all the users for each house we can now set lStatus = tempvar.
The tempvar should then be reset to 0 for the next house.
You should try to avoid loops and other procedural constructs when coding SQL. A relational database can't easily optimize such things and they often perform orders of magnitude slower than their declarative counterparts. In this case, it seems simple enough to replace your SUM(code) with the CASE statement that you describe:
UPDATE Houses
SET lStatus = U.codesum
FROM Houses H
JOIN (SELECT ref, SUM(CASE code WHEN 1 THEN 5 WHEN 2 THEN 10 ELSE 0 END) AS codesum
FROM Users
GROUP BY ref) AS U ON U.ref = H.ref
In this way, SUM can still handle the duty that you imagine your temp variable would be doing.
Also, if you have many cases, you might think about putting those in a table and simply joining on that to get your sum. This might be better to maintain. I'm using a table variable here, but it could look like the following:
DECLARE #codes TABLE (
code INT NOT NULL PRIMARY KEY,
value INT NOT NULL
)
INSERT INTO #codes SELECT 1, 5
INSERT INTO #codes SELECT 2, 10
UPDATE Houses
SET lStatus = U.codesum
FROM Houses H
JOIN (SELECT a.ref, SUM(b.value) AS codesum
FROM Users a
JOIN #codes b on a.code = b.code -- Here we get the values dynamically
GROUP BY a.ref) AS U ON U.ref = H.ref
Try this:
UPDATE Houses
SET lStatus = U.codesum
FROM Houses H
JOIN (
SELECT ref, SUM(
CASE
WHEN Code = 1
THEN 5
WHEN Code = 2
THEN 10
END
) AS codesum
FROM Users
GROUP BY ref
) AS U ON U.ref = H.ref
Try this :
UPDATE Houses
SET lStatus = U.code
FROM Houses H
JOIN (
SELECT ref, SUM(
CASE
WHEN Code = 1
THEN 5
WHEN Code = 2
THEN 10
ELSE 0
END
) AS code
FROM Users
GROUP BY ref
) AS U ON U.ref = H.ref

SQL Server order by query

I have two tables called Listing and ListingProperties
Listing (ID, CurrentPrice)
ListingProperties (id, listingId, Fixedprice)
The problem is I want to order all listings by Fixedprice. But some listings don't have a Fixedprice.
In that case I want to check current price and compare with others Fixedprice and then order.
Listing
id name currentprice
1 a 10
2 b 50
3 c 40
ListingProperties
id listingId Fixedprice
1 1 20
2 3 30
after order the required order is
name
a
c
b
Try this:
SELECT Name
FROM Listing l
LEFT JOIN ListingProperties lp ON l.id=lp.listingid
ORDER BY ISNULL(lp.FixedPrice, l.currentprice)
Your question is not clear but I'll try to guess.
1) You have to join your tables:
SELECT <fields here>
FROM Listing L
LEFT JOIN ListingProperties LP
ON L.ID = LP.ListingId
This query assumes that you dont have REPEATED VALUES for a ListingId in ListingProperties. If you do have multiple values you have to specify priority criteria to decide which FixedPrice you want to show.
2) Once you have the joined query, you have to use the CASE statetemnt to select betwheen current and fixed. Tis assumes that you have AT LEAST ONE record in Listing for every item you want to list. If you do not have at least one, you'll have to do some forther tricks.
SELECT CASE WHEN L.CurrentPrice IS NULL THEN LP.FicedPrice ELSE L.CurrentPrice END
FROM Listing L
LEFT JOIN ListingProperties LP
ON L.ID = LP.ListingId
ORDER BY CASE WHEN L.CurrentPrice IS NULL THEN LP.FicedPrice ELSE L.CurrentPrice END

Resources