Background:
i was first asked to do a website using mysql as the database, after that was done and sent, the clients asked me to convert it to mssql, and 3 tiers.
i did the classes and functions for transferring data between the servers, so the 3 tiers bit is about halfway done. the thing i’m struggling with now is the MsSQL.
Question:
the MySQL version of the question looks like this:
select a.id as a_id, a.first_name, a.last_name, a.agent_code,
b.id as b_id, b.user_id, b.status_admin
from tbl_user a
inner join tbl_testimonia b
on a.id = b.user_id
where b.status_admin=0
group by a.id
order by b.id desc
what it does is return testimonials that aren’t approved yet, grouped to each user;
Where I am stuck:
i cant convert this to MSSQL
My best try:
- Create view;
as in:
create view test as
(
select a.id as a_id, a.first_name, a.last_name, a.agent_code,
b.id as b_id, b.user_id, b.status_admin
from tbl_user a inner join tbl_testimonia b on a.id = b.user_id
where b.status_admin=0 and a.id in
(
select a.id from tbl_user a
inner join tbl_testimonia b
on a.id = b.user_id
where b.status_admin=0
group by a.id
)
)
this selects what i want, but the id field of the create view cant be grouped, meaning the id field is not unique and can have the same value.
I guess my question up to this point is, how do i uniquely select the id field in the view?
sure i can do it in PHP, but i could have done that a month ago when i first encountered the problem.
I’ve been trying to find the answer for a while now but cant seem to find the answer unique to my question
- edit: the MSSQL doesn’t work because even though the subquery is selecting unique ids the in statement in the main query makes this irrelevent
-
edit: example output::~ (in MySql the 3rd field is ommited)
| a_id | firstN | LastN | agent_code | b_id | user_id |status_admin| +--------------------------------------------------------------------------+ | 32 | fn1 | ln1 | AC123213 | 14 | 32 | 0 | | 41 | fn2 | ln2 | 12345678 | 15 | 41 | 0 | | 32 | fn1 | ln1 | AC123213 | 16 | 32 | 0 | -
edit: QUESTION SOLVED a big thx to Lieven for the simple answer
As you have already explained yourself, unlike SQL Server, MySQL allows grouping by with unaggregated expressions like this
As an unaggregated expression in GROUP BY returns an arbitrary record from each group and is not supposed to be used if the values vary you should be able to use the following statement as an equivalent in SQL Server